O segredo aqui está em entender o output da função gather
. Vejamos ele em detalhes abaixo.
df <- read.table(
text = "c1 c2 c3 x
2 4 5 0
3 5 2 0
6 7 8 0
1 2 5 1
2 5 6 1
3 3 3 1", header = TRUE)
library(tidyverse)
df %>% gather("id", "value", 1:3)
#> x id value
#> 1 0 c1 2
#> 2 0 c1 3
#> 3 0 c1 6
#> 4 1 c1 1
#> 5 1 c1 2
#> 6 1 c1 3
#> 7 0 c2 4
#> 8 0 c2 5
#> 9 0 c2 7
#> 10 1 c2 2
#> 11 1 c2 5
#> 12 1 c2 3
#> 13 0 c3 5
#> 14 0 c3 2
#> 15 0 c3 8
#> 16 1 c3 5
#> 17 1 c3 6
#> 18 1 c3 3
Note que há 3 colunas. Usaremos x
e value
para tomarem os valores de x
e c1
, c2
e c3
do conjunto original, fazendo com que id
seja o identificador de cada coluna no formato longo. Assim, temos o seguinte gráfico:
df %>% gather("id", "value", 1:3) %>%
ggplot(., aes(x = x, y = value, colour = id)) +
geom_point()

Note que não dá para perceber muita coisa em relação à correlação de c1
, c2
e c3
com x
, pois x
só tem dois valores. Uma maneira de resolver isso é ajustando uma curva a cada valor de id
. Neste caso, optei por uma regressão linear simples e a visualização melhorou um pouco.
df %>% gather("id", "value", 1:3) %>%
ggplot(., aes(x = x, y = value, colour = id)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
#> `geom_smooth()` using formula 'y ~ x'

Outra forma seria dividindo os id
em painéis, para ao menos separar melhor os grupos de pontos e facilitar a visualização de tendências.
df %>% gather("id", "value", 1:3) %>%
ggplot(., aes(x = x, y = value)) +
geom_point() +
facet_wrap(~ id)

Created on 2021-07-28 by the reprex package (v2.0.0)