我想在图例中包含平均值的符号以及方框的符号。所以我的图例应该包括“Exposure 1,Exposure 2,Exposure 3”,而且还包括单词mean及其符号。如何在 R 中使用 ggplot 来做到这一点?
这是我用来生成箱线图的代码:
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)
数据可在https://my.cloudme.com/josechka/mydata获取
上面的代码生成一个箱线图,箱内包含平均值。然而图例仅包含类别符号。我需要的是添加到图例中,框内的后点代表每个类别的平均值。可以做到吗?
最佳答案
您可以添加一个geom_point
,并将单独的aes
定义为“mean”,从而创建一个新的图例。默认情况下,这将绘制所有单独的数据点,但将 alpha 设置为零会使这些点在图表中不可见,而使用 override.aes 则让点符号出现在传奇。
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)))
关于r - 如何使用 ggplot 在箱线图中包含平均值的图例符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26756358/