我的问题如下:在R包中ggplot2
-箱线图 -如何标记 mustache 末端的两个点(上部和下部),例如用“x”标记,这样最终得到一个箱线图和两个额外的“x”标记,位于 mustache 的最上端,另一个标记位于下 mustache 的最下端。
我在互联网上搜索了很多答案,但找不到。我只能使用 stat_summary 和平均函数数据在箱线图上添加“x”标记。
另外两点怎么办?
要在同一页面上,请使用R的mtcars
数据库并将mpg
的boxplot
作为y轴和cyl
作为 x 轴。根据数据框 mtcars
,Yu 最终会得到 3 个箱线图。
根据R
The upper end defined as Q3+1.5*IQR
The lower end defined as Q1-1.5*IQR
Note: IQR = Q3 - Q1
最佳答案
您只需使用stat_summary
计算箱线图的端点并添加它们。例如
##Load the library
library(ggplot2)
data(mpg)
##Create a function to calculate the points
##Probably a built-in function that does this
get_tails = function(x) {
q1 = quantile(x)[2]
q3 = quantile(x)[4]
iqr = q3 -q1
upper = q3+1.5*iqr
lower = q1-1.5*iqr
if(length(x) == 1){return(x)} # will deal with abnormal marks at the periphery of the plot if there is one value only
##Trim upper and lower
up = max(x[x < upper])
lo = min(x[x > lower])
return(c(lo, up))
}
使用stat_summary
将其添加到您的图中:
ggplot(mpg, aes(x=drv,y=hwy)) + geom_boxplot() +
stat_summary(geom="point", fun.y= get_tails, colour="Red")
此外,您对终点的定义不太正确。看我的answer到另一个问题了解更多细节。
关于r - 在 R 统计中的 ggplot2 中标记每个箱线图中两条 mustache 的末端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9843660/