r - ggplot2如何在geom_bar图中创建与分位数相对应的垂直线

标签 r ggplot2 quantile geom-bar

目前,我可以创建如下图:

geom_bar

ggplot(df.Acc, aes(x = reorder(cities, -accidents), y = accidents)) +
geom_bar(stat = "identity", fill="steelblue", alpha=0.75) + 
geom_hline(yintercept=0, size=0.4, color="black")

假设该图的 y 轴为每年的自行车事故数量,x 轴为城市名称。

我想添加一条垂直线来分隔 70% 以上和以下的所有城市。

所以我尝试过

> vlinAcc <- quantile(df.Cities$accidents, .70)
> vlinAcc
     70% 
41.26589 

这看起来不错,所有事故值(value)高于 41 的城市都在第 70 个百分位以上。

但是,我不知道如何将其添加到图表中。我尝试过:

+ geom_vline(xintercept=vlinAcc, size=0.4, color="black")

但是,当然,垂直线在第 41 个城市处截取 x,而不是在 y 值为 41.265 的地方截取。这不是我想要的。如何定位该线以便与具有第 70 个百分位值的城市相对应,而不是在错误的位置创建垂直线?

我的数据框包含一列,其中包含事故值,城市被设置为行名称,我将其复制到新列,以便可以将它们用作 x 轴上的标签。

最佳答案

看起来您需要在城市按 y 值排序后找到第 70 个百分位数城市的 x 位置。以下是使用内置 mtcars 数据框的示例。 geom_vline 代码按照我们对条形图排序的顺序对 mpg(本例中为 y 值)进行排序,然后找到 mpg 的索引 最接近第 70 个百分位数的值。这就是我们想要垂直线的 x 位置:

mtcars$model = rownames(mtcars)

ggplot(mtcars, aes(reorder(model, -mpg), mpg )) + 
  geom_bar(stat="identity", fill="lightblue") +
  theme_bw() +
  geom_vline(xintercept = which.min(abs(sort(mtcars$mpg,decreasing=TRUE) - quantile(mtcars$mpg,0.7)))) +
  theme(axis.text.x=element_text(angle=-90, vjust=0.5,hjust=0))

enter image description here

您还可以用水平线标记第 70 个百分位数,这可能更具启发性。

ggplot(mtcars, aes(reorder(model, -mpg), mpg )) + 
  geom_bar(stat="identity", fill="lightblue") +
  theme_bw() +
  geom_hline(yintercept = quantile(mtcars$mpg, .7), lty=2) +
  theme(axis.text.x=element_text(angle=-90, vjust=0.5,hjust=0)) 

enter image description here

关于r - ggplot2如何在geom_bar图中创建与分位数相对应的垂直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37280407/

相关文章:

r - 使用 `plotmath` 显示下标和 `[ ]` 的组合

r - 计算大数据的分位数

JavaScript:可以通过给定的 z 分数获得百分位吗?计算分位数?

r - 如何跳过阅读readr中的某些列

r - 升级到 2.0 版后 ggplot2 错误

r - ggplot2 中的 geom_text() 大小定义

r - 中间有 y 轴的多面 ggplot

python - 从 pandas qcut 间隔中删除小数点(将间隔转换为整数)

rjags 错误 mat[, "deviance"] : subscript out of bounds 中的错误

r - 用 R 中的置信区间计算亚组的年龄标准化率