0

使用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 创建的未评估映射列表

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

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

最后,我想将 n 添加到 x 轴的标签(即M2 (n=3))。我可以使用以下代码在常规 R 中执行此操作:names=paste(b$names, "(n=", b$n,")")), where b= boxplotfunction,但我不知道如何在ggplot2

4

1 回答 1

2

您需要在 中明确命名参数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']])
于 2013-05-15T00:59:19.930 回答