ggplot2 How to create vertical line corresponding to quantile in geom_bar plot

这一生的挚爱 提交于 2019-12-06 04:08:32

It looks like you need to find the x-position of the 70th percentile city after the cities have been ordered by their y-value. Here's an example of that with the built-in mtcars data frame. The geom_vline code sorts mpg (the y-value in this case) in the same order as we've sorted the bars and then finds the index of the mpg value that's nearest to the 70th percentile. That's the x-position of where we want the vertical line:

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))

You could also mark the 70th percentile with a horizontal line, which might be more illuminating.

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)) 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!