how to include in legend symbol of mean in boxplot with ggplot?

元气小坏坏 提交于 2019-12-11 05:19:30

问题


I would like to have in the legend the symbol of the mean together with the symbols of the boxes. So my legend should include "Exposure 1, Exposure 2, Exposure 3" but also the word mean and its symbol. How to do this using ggplot in R?

This is the code I'm using to produce the boxplot:

library(ggplot2)
mydata <- read.csv("~/mydata.csv")
bp<-ggplot(mydata,aes(x=Category,y=MeanValues,,fill=as.factor(Category))) + geom_boxplot()
bp+labs(x = NULL, y = "Result")+ theme_bw()+stat_summary(fun.y = mean, geom = "point",shape = 19, size = 3,show_guide = FALSE)+theme(legend.position="top")+ guides(fill=guide_legend(title=NULL))+ theme(axis.title.y = element_text(size=20, colour = rgb(0,0,0)),axis.text.y = element_text(size=12, colour = rgb(0,0,0)),axis.text.x = element_text(size=12, colour = rgb(0,0,0)))+scale_y_continuous(limits = c(0, 1800), breaks = 0:1800*200)

The data is available at https://my.cloudme.com/josechka/mydata

The above code produces a boxplot with the mean values inside the boxes. However the legend only contains the symbols of categories. What I need is to add to the legend that the back points inside the boxes represent the mean value of each category. Is it possible to do it?


回答1:


You could add a geom_point with separate aes defined as ''mean'', thereby creating a new legend. With defaults, this would plot all the individual data points, but setting alpha to zero makes the points invisible in the graph, while using override.aes lets the point symbol appear in the legend.

bp<-ggplot(mydata,aes(x=Category,y=MeanValues,,fill=as.factor(Category))) + 
  geom_boxplot()
bp+ labs(x = NULL, y = "Result")+ theme_bw()+
  stat_summary(fun.y = mean, geom = "point",shape = 19, size = 3,show_guide = FALSE)+
  theme(legend.position="top")+ guides(fill=guide_legend(title=NULL))+ 
  theme(axis.title.y = element_text(size=20, colour = rgb(0,0,0)),axis.text.y = element_text(size=12, colour = rgb(0,0,0)),axis.text.x = element_text(size=12, colour = rgb(0,0,0)))+
  scale_y_continuous(limits = c(0, 1800), breaks = 0:1800*200)+
  geom_point(aes(shape = "mean"), alpha = 0)+  # <-- added this line of code and next
  guides(shape=guide_legend(title=NULL, override.aes = list(alpha = 1)))



来源:https://stackoverflow.com/questions/26756358/how-to-include-in-legend-symbol-of-mean-in-boxplot-with-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!