0

So I am making a ggplot graph with grouped boxplots, which also have overlaid geom_point, and I want the geom_points to be connected with lines. This is my code currently:

#my dataframe
dataset = c(rep("1",33),rep("2",15))
pairs_summary = c(rep(c("Other","Peak","Trough"),16))
unique_mouse = rep(letters[1:16], each = 3)
proportion = c(55.319149, 12.765957, 31.914894, 65.730337, 14.044944, 20.224719, 55.357143, 3.571429, 41.071429, 59.872611, 18.789809, 21.337580,
               70.833333, 20.833333, 8.333333, 41.935484, 9.677419, 48.387097, 61.904762, 9.523810, 28.571429, 61.507937, 15.873016, 22.619048,
               57.894737,  5.263158, 36.842105, 54.935622,  9.012876, 36.051502, 55.263158, 18.947368, 25.789474, 50.892857, 27.678571, 21.428571,
               38.297872, 20.212766, 41.489362, 43.859649, 36.363636, 19.776715, 63.013699, 27.397260,  9.589041, 36.842105, 63.157895, 0.000000)
df = data.frame(dataset,pairs_summary,unique_mouse,proportion)

#the plot
df %>% 
  ggplot(aes(x=reorder(pairs_summary,proportion), y=proportion, fill=pairs_summary,colour=as.factor(dataset)))+
  geom_boxplot(outlier.shape=NA,width=0.15,alpha=0.8,position = position_dodge(0.4))+
  geom_point(aes(fill=pairs_summary,colour=as.factor(dataset)),position=position_dodge(0.4),shape=21)+
  geom_line(aes(linetype=as.factor(dataset),group=unique_mouse),position=position_dodge2(0.4))+
  theme_minimal()+
  theme(legend.position="none")+
  scale_fill_manual(values=c("gray32","#f59a2f","#5c1363"))+
  scale_colour_manual(values=c("black","black"))+
  labs(y="Percent of cells (%)",x="")

This produces almost what I want: Graph

but the lines don't really match the points. How can I make the geom_line actually connect the dodged geom_point, instead of just kinda being in the general vicinity?

1 Answers1

1

Well, I solved it in an arguably kinda dumb way, but here it is:

df %>% 
  ggplot(aes(x=reorder(pairs_summary,proportion), y=proportion, fill=pairs_summary,colour=as.factor(dataset)))+
  geom_boxplot(outlier.shape=NA,width=0.15,alpha=0.8,position = position_dodge(0.4))+
  geom_point(aes(fill=pairs_summary,colour=as.factor(dataset)),position=position_dodge(0.4),shape=21)+
  geom_line(data=(df %>% filter(dataset==1)),aes(group=unique_mouse),position=position_dodge(0.2,preserve="single"))+
  geom_line(data=(df %>% filter(dataset==2)),aes(group=unique_mouse),position=position_dodge(-0.2,preserve="single"),linetype=2)+
  theme_minimal()+
  theme(legend.position="none")+
  scale_fill_manual(values=c("gray32","#f59a2f","#5c1363"))+
  scale_colour_manual(values=c("black","black"))+
  labs(y="Percent of cells (%)",x="")

I don't really know what it does exactly, but separating the geom line call into two, and adding preserve="single" works

graph 2