r - 在 R 统计中的 ggplot2 中标记每个箱线图中两条 mustache 的末端

标签 r ggplot2

我的问题如下:在R包中ggplot2 -箱线图 -如何标记 mustache 末端的两个点(上部和下部),例如用“x”标记,这样最终得到一个箱线图和两个额外的“x”标记,位于 mustache 的最上端,另一个标记位于下 mustache 的最下端。

我在互联网上搜索了很多答案,但找不到。我只能使用 stat_summary 和平均函数数据在箱线图上添加“x”标记。

另外两点怎么办?

要在同一页面上,请使用R的mtcars数据库并将mpgboxplot作为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/

相关文章:

r - 使用过滤数据计算分类平均值

r - 保留组合条形图中缺失列的位置

r - 如何安装 Caret 包?安装时,我收到此消息

r - geom_vline 的行为是否与其他 ggplot geom 的行为不一致?

R - ggplot2 geom_area 只有一个类别可见?

r - 如何在r中转义百分比 '%'的符号?

r - 在ggplot2中的条形之间绘制百分比线

R:根据另一列操作一个数据框列的值

区域多边形未显示在 ggplot2 Choropleth map 中

r - 如何更好地从 ggplot2 创建具有多个变量的堆叠条形图?