18

有没有办法在 R 中创建一个箱线图,该箱线图将与箱(某处)一起显示“N =(样本大小)”?varwidth 逻辑根据样本大小调整框的宽度,但这不允许在不同的图之间进行比较。

FWIW,我以下列方式使用 boxplot 命令,其中“f1”是一个因素:

boxplot(xvar ~ f1, data=frame, xlab="input values", horizontal=TRUE)
4

5 回答 5

33

这是一些ggplot2代码。它将以样本均值显示样本大小,使标签具有多功能性!

首先,一个简单的函数fun.data

give.n <- function(x){
   return(c(y = mean(x), label = length(x)))
}

现在,用钻石数据来演示

ggplot(diamonds, aes(cut, price)) + 
   geom_boxplot() + 
   stat_summary(fun.data = give.n, geom = "text")

您可能必须调整文本大小以使其看起来不错,但现在您有一个样本大小的标签,它也给人一种倾斜的感觉。

于 2010-08-14T14:07:16.330 回答
11

您可以使用names参数在n每个因子名称旁边写入。

如果您不想n自己计算,可以使用这个小技巧:

# Do the boxplot but do not show it
b <- boxplot(xvar ~ f1, data=frame, plot=0)
# Now b$n holds the counts for each factor, we're going to write them in names
boxplot(xvar ~ f1, data=frame, xlab="input values", names=paste(b$names, "(n=", b$n, ")"))
于 2010-08-14T12:59:59.863 回答
5

要获得该n栏的顶部,您可以使用boxplot 提供textstat详细信息,如下所示

b <- boxplot(xvar ~ f1, data=frame, plot=0)
text(1:length(b$n), b$stats[5,]+1, paste("n=", b$n))

b 的 stats 字段是一个矩阵,每一列包含一个组/图的下须线的极值、下铰链、中值、上铰链和上须线的极值。

于 2014-11-21T18:57:54.097 回答
1

gplots包提供boxplot.n,根据文档产生一个箱线图,注释有观察的数量

于 2013-06-27T10:59:47.593 回答
0

我想出了一个使用 Envstats 包的解决方法。需要使用以下方式下载、加载和激活此软件包:

library(Envstats)

stripChart(与 stripchart 不同)确实向图表添加了一些值,例如 n 值。首先,我绘制了我的箱线图。然后我在 stripChart 中使用了 add=T。显然,很多东西都隐藏在 stripChart 代码中,因此它们不会出现在箱线图上。这是我用于 stripChart 隐藏大多数项目的代码。

带有集成条形图的箱线图以显示 n 值:

stripChart(data.frame(T0_G1,T24h_G1,T96h_G1,T7d_G1,T11d_G1,T15d_G1,T30d_G1), show.ci=F,axes=F,points.cex=0,n.text.line=1.6,n.text.cex=0.7,add=T,location.scale.text="none")

所以箱线图

boxplot(data.frame(T0_G1,T24h_G1,T96h_G1,T7d_G1,T11d_G1,T15d_G1,T30d_G1),main="All Rheometry Tests on Egg Plasma at All Time Points at 0.1Hz,0.1% and 37 Set 1,2,3", names=c("0h","24h","96h","7d ", "11d", "15d", "30d"),boxwex=0.6,par(mar=c(8,4,4,2)))

然后条形图

stripChart(data.frame(T0_G1,T24h_G1,T96h_G1,T7d_G1,T11d_G1,T15d_G1,T30d_G1), show.ci=F,axes=F,points.cex=0,n.text.line=1.6,n.text.cex=0.7,add=T,location.scale.text="none")

您始终可以调整数字的高位(n 值),以便它们适合您想要的位置。

于 2016-11-10T09:37:26.370 回答