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

三世轮回 提交于 2019-12-07 18:45:06

问题


Currently, I can create a plot such as this:

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

It's a plot with, let's say, number of bike accidents per year on the y-axis, and the city name would be on the x-axis.

I want to add a vertical line to separate all the cities above the 70th percentile and below it.

So I've tried with

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

This looks good, all the cities which have value of accidents above 41 are above the 70th percentile.

However, I don't know how to add this to the chart. I tried with:

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

But then, of course, the vertical line intercepts the x at the 41th city, instead of where the y value is 41.265. Which is not what I want. How do I position the line in order to correspond to the city which has the value of the 70th percentile, instead of creating the vertical line at the incorrect place?

My data frame contains one column with values for the accidents and the cities are set as row names which I duplicated to a new column to make it possible to use them as labels on the x-axis.


回答1:


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



来源:https://stackoverflow.com/questions/37280407/ggplot2-how-to-create-vertical-line-corresponding-to-quantile-in-geom-bar-plot

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