1

I have a grouped boxplot that shows for each category two boxes side by side (see code). Now I am interested in adding the mean for each category and box separately. I can calculate and visualize the mean for each category but not conditioned on the grouped variable "year". I tried to calculate the means for each year individually and add them separately, but that did not work.

data(mpg, package = "ggplot2") 
library(latticeExtra)
tmp <- tapply(mpg$hwy, mpg$class, FUN =mean)
bwplot(class~hwy, data = mpg, groups = year,
       box.width = 1/3,
       panel = panel.superpose,
       panel.groups = function(x, y,..., group.number) {
         panel.bwplot(x,y + (group.number-1.5)/3,...)
         panel.points(tmp, seq(tmp),...)
       }
) 

Which produces the following plot:

Boxplot

The example is based on: Grouped horizontal boxplot with bwplot

Can someone show how to do this if possible using Lattice graphics? Because all my plots in my master thesis are based on it.

bad_coder
  • 11,289
  • 20
  • 44
  • 72

1 Answers1

0

If you want to consider a last option, you can try with ggplot2. Here the code where the red points belong to means:

library(ggplot2)
library(dplyr)
#Data
data(mpg, package = "ggplot2") 
#Compute summary for points
Avg <- mpg %>% group_by(class,year) %>%
  summarise(Avg=mean(hwy))
#Plot
ggplot(data = mpg, aes(x = class, y = hwy, fill = factor(year))) +
  geom_boxplot(alpha=.25) +
  geom_point(data=Avg,aes(x = class, y = Avg,color=factor(year)),
             position=position_dodge(width=0.9),show.legend = F)+
  scale_color_manual(values = c('red','red'))+
  coord_flip()+
  labs(fill='Year')+
  theme_bw()

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
  • Hi @Duck thanks for you reply. It helps for the discussions with my prof. But as I mentioned I would prefer the Lattice Plot =) – Mino Müller Oct 22 '20 at 11:20