r - 如何使用 ggplot 在箱线图中包含平均值的图例符号?

标签 r ggplot2 legend boxplot

我想在图例中包含平均值的符号以及方框的符号。所以我的图例应该包括“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)))

enter image description here

关于r - 如何使用 ggplot 在箱线图中包含平均值的图例符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26756358/

相关文章:

python - 如何在 Windows 操作系统中从 R 调用 Python?

r - 仅根据列中的 "YES"或 "NO"绘制选定的行

r - 在 ggplot2 上使用百分比刻度时如何设置中断?

python - seaborn:带有背景颜色的图例

javascript - 如何反转 Flot 堆积条形图中的图例标签?

python - 如何更改图例中字体的文本颜色?

r - 用准引用命名新列时可以使用函数吗?

r - 当系列中的所有值都相同时,geom_violin 会产生错误

r - 将字体大小调整为绘图设备的大小

r - 操纵 Y 轴限制不起作用(ggplot2 百分比条形图)