如何将值放在箱线图上并控制其宽度?
X<-c(1,2,,3,4,4,5,5,6,6,6,6,6,7)
我需要写下最小值、最大值、第一个四分位数、中位数和最后一个四分位数的值。我怎么能把它放在那里?
您可以使用horizontal = TRUE
获取水平箱线图并axes = FALSE
删除轴。staplewex = 1
将装订宽度设置为与盒子宽度相同
然后你可以使用fivenum
返回用于创建箱线图的统计数据并将它们用作文本标签,摆弄y
值直到你得到你想要的
boxplot(X, horizontal = TRUE, axes = FALSE, staplewex = 1)
text(x=fivenum(X), labels =fivenum(X), y=1.25)
请注意,我3
为您的示例数据中缺少的值插入了一个X
mnel 提供的答案是完美的,假设(如示例中所示)没有异常值。在这种情况下,下须和上须分别等于最小值和最大值。但是,如果存在异常值并且我们没有range = 0
在箱线图函数中指定,我们将无法获得正确的标签值。相反,我们可以使用:
text(x=boxplot.stats(X)$stats, labels = boxplot.stats(X)$stats, y = 1.25)
让我们看一个例子:
横向
X <- c(1,2,3,3,4,4,5,5,6,6,6,6,10,15)
boxplot(X, horizontal = TRUE, axes = FALSE, staplewex = 1)
text(x = fivenum(X), labels = fivenum(X), y = 1.25)
text(x = boxplot.stats(X)$stats, labels = boxplot.stats(X)$stats, y = 1.25)
垂直
在内部切换 x 和 y 的参数text
。
boxplot(X, axes = FALSE, staplewex = 1)
text(y = boxplot.stats(X)$stats, labels = boxplot.stats(X)$stats, x = 1.25)
我在尝试理解箱线图四分位数标签并与汇总函数值进行比较时遇到了一些问题,所以我想与您分享。
有时,与 r 汇总函数值相比,使用 Fivenum 或 stats 的箱线图中的四分位数标签会有所不同。这仅发生在偶数数据集上。
例如(使用文本(x = boxplot.stats(X)$stats, labels = boxplot.stats(X)$stats, y = 1.25)):
product<-c(3,12,20,25,30,35,70,70,80,150)
summary(product)
Min. 1st Qu. Median Mean 3rd Qu. Max.
3.00 21.25 32.50 49.50 70.00 150.00
boxplot(product,horizontal=TRUE,col="grey",staplewex=1,axes=FALSE)
text(x = boxplot.stats(product)$stats, labels = boxplot.stats(product)$stats, y = 1.25)
正如您在图片中看到的,这些值不匹配。
在这种情况下,您可以使用分位数功能:
text(x=quantile(produto),labels=quantile(produto),y=1.25)
现在您应该得到与汇总函数中列出的相同的值。否则,只需忽略汇总函数并改用 FiveNum 值。出现差异的原因是统计学家之间缺乏普遍共识。
谷歌搜索将显示分位数计算的差异。
boxplot(X, axes = FALSE, staplewex = 1)
text(y = boxplot.stats(X)$stats, labels = boxplot.stats(X)$stats, x = 1.25)
如何做到这一点,但在多个箱线图中
示例数据:
a <- data.frame(
Rank = c(1,2,3,1,2,3,1,2,3,3,2,1,3,2,1,2,1,3,3,3,1,1,2,2,1,3 ),
Time = c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3),
Value = c(5,10,15,20,30,50,70,80,100,5,7,9,11,15,17,19,17,19,100,200,300,400,500,700,1000,200))
boxplot(a$Value[a$Rank==1] ~ a$Time[a$Rank==1])