【问题标题】:how to include in legend symbol of mean in boxplot with ggplot?如何在带有ggplot的箱线图中包含平均值的图例符号?
【发布时间】:2014-11-05 11:40:15
【问题描述】:

我想在图例中包含均值符号和方框符号。所以我的图例应该包括“曝光 1,曝光 2,曝光 3”,还有意思这个词和它的符号。如何在 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获取

上面的代码生成了一个箱线图,箱内有平均值。然而,图例只包含类别的符号。我需要在图例中添加框内的后点代表每个类别的平均值。有可能吗?

【问题讨论】:

  • 您能提供到目前为止的代码吗?此外,如果可能,请提供一个图例示例,显示您所描述的内容。

标签: r ggplot2 legend boxplot


【解决方案1】:

您可以添加一个 geom_point 并将单独的 aes 定义为“平均”,从而创建一个新的图例。默认情况下,这将绘制所有单独的数据点,但将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)))

【讨论】:

    猜你喜欢
    • 2013-09-03
    • 2012-08-31
    • 2021-07-01
    • 2023-04-03
    • 2018-06-17
    • 2021-01-21
    • 2021-11-25
    • 2019-04-02
    • 1970-01-01
    相关资源
    最近更新 更多