Nick Allen
Nick Allen

Reputation: 1467

ggplot2 - Overlay Mean of Each Group

I am trying to mimic this lattice plot using ggplot. The data for this plot is lme4::Dyestuff.

enter image description here

I am able to plot each of the points in a similar manner, but I am unable to plot the line which represents the mean of each batch.

library (lme4)
library (ggplot2)

ggplot (Dyestuff, aes (Yield, Batch, colour = Batch)) + geom_jitter ()

Q. How can I add this line using ggplot? Notice also how the batches on the y-axis are ordered by the mean yield of the batch.

Upvotes: 2

Views: 1243

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98589

One solution is to use Batch as x values and Yield as y values. Line is added with stat_summary() and argument fun.y=mean to get mean value of Yield. Then coord_flip() is used to get Batch as y axis. To change order of Batch values you can use reorder() function inside the aes() of ggplot().

ggplot (Dyestuff, aes (reorder(Batch,Yield), Yield)) + geom_jitter(aes(colour=Batch))+ 
  stat_summary(fun.y=mean,geom="line",aes(group=1))+
  coord_flip()

enter image description here

Upvotes: 4

Related Questions