【问题标题】:adding geom_hline+ Sample Size to a boxplot将 geom_hline+ 样本大小添加到箱线图中
【发布时间】:2013-05-15 00:11:56
【问题描述】:

使用ggplot,我正在尝试

  1. 在箱线图中添加一条水平线
  2. 将样本大小添加到 x 轴。

我有以下数据集:

Site, Aluminum_Dissolved, Federal_Guideline
M1, 0.1, 0.4
M1, 0.2, 0.4
M1, 0.5, 0.4
M2, 0.6, 0.4
M2, 0.4, 0.4
M2, 0.3, 0.4

添加水平线

#Make a boxplot with horizontal error bars
ggplot(ExampleData, aes(x = Site,y = Aluminum_Dissolved))+
    stat_boxplot(geom='errorbar', linetype=1)+
    geom_boxplot(fill="pink")

#Now want to add guideline value at 0.4 with corresponding "Federal Guideline" in legend, I tried:
geom_hline(0.4)

我收到以下错误:

get(x, envir = this, inherits = inh)(this, ...) 中的错误: 映射应该是由 aes 或 aes_string 创建的未评估映射列表

我尝试在字符串中添加数据,即geom_hline("ExampleData$Federal_Guideline),但我得到与上面相同的错误。

添加样本大小(n= 到 x 轴):

最后,我想将 n 添加到 x 轴的标签(即M2 (n=3))。我可以使用以下代码在常规 R 中执行此操作:names=paste(b$names, "(n=", b$n,")")),其中 b=boxplot 函数,但我无法弄清楚如何在 ggplot2 中执行此操作

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你需要明确命名geom_hline中的参数,否则它不知道0.4指的是什么。

    所以

    ggplot(ExampleData, aes(x = Site,y = Aluminum_Dissolved))+
        stat_boxplot(geom='errorbar', linetype=1)+
        geom_boxplot(fill="pink") +
        geom_hline(yintercept = 0.4)
    

    会产生你需要的水平线。

    要更改 x 轴上的标签,请使用 scale_x_discrete 更改标签

    你可以使用类似的东西预先计算这些

    library(plyr)
    xlabels <- ddply(ExampleData, .(Site), summarize, 
                     xlabels = paste(unique(Site), '\n(n = ', length(Site),')'))
    
    ggplot(ExampleData, aes(x = Site,y = Aluminum_Dissolved))+
         stat_boxplot(geom='errorbar', linetype=1)+
         geom_boxplot(fill="pink") + geom_hline(yintercept = 0.4) + 
          scale_x_discrete(labels = xlabels[['xlabels']])
    

    【讨论】:

    • 非常感谢您清晰的编辑和回答!我添加了 + geom_hline(yintercept=0.4, linetype=2, colour="red") 来获取我正在寻找的线。我尝试添加: show_guide=TRUE 以显示图例,但无济于事。我犯了某种语法错误吗?
    • 另外,'n' 编码工作得很好......谢谢。我自己也想不通。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多