Connecting the points of a dodged geom_point by group

Viewed 295

Consider this nested data set, in which i aim at plotting the two nested factor variables on the x-axis:

df <- data.frame(X=c(rep("A",9), rep("B",9), rep("C",9)),
                 nested=c(rep(c(rep("X",3), rep("Y",3), rep("Z",3)),3)),
                 response=runif(27))

ggplot(df) +
  geom_point(aes(x=X, y=response, col=nested, group=nested, shape=nested), position=position_dodge(width=1))

I want to connect the dots in each level of nested in each level of X to have vertical, parallel lines in the plot, spanning from the maximum to the minimum of response in each nested level. (much alike i would use fill=nested if would go for boxplots), but my first approach was not satisfactory:

ggplot(df) +
  geom_point(aes(x=X, y=response, col=nested, group=nested, shape=nested), position=position_dodge(width=0.3))+
  geom_line(aes(x=X, y=response, col=nested, group=nested))

I can imagine using geom_errorbar, but this means i would need to create a separate dataframe with min and max values, correct?

2 Answers

You can dodge the lines too. Just make sure that the group aesthetic is mapped to the interaction between nested and X:

ggplot(df) +
  geom_point(aes(x = X, y = response, col = nested, shape = nested), 
             position=position_dodge(width = 0.3)) +
  geom_line(aes(x = X, y = response, col = nested, 
                group = interaction(nested, X)),
            position = position_dodge(width = 0.3))

enter image description here

Maybe try this approach with facet_wrap():

library(ggplot2)
#Code
ggplot(df) +
  geom_point(aes(x=X, y=response,
                 col=nested, group=nested, shape=nested),
             position=position_dodge(width=1))+
  geom_line(aes(x=X, y=response,
                col=nested,group=nested),position=position_dodge(width=1))+
  facet_wrap(.~X,scales='free_x')+
  theme(strip.background = element_blank(),
        strip.text = element_blank())

Output:

enter image description here

Related