ggplot2如何在geom_bar图中创建与分位数对应的垂直线 [英] ggplot2 How to create vertical line corresponding to quantile in geom_bar plot

查看:264
本文介绍了ggplot2如何在geom_bar图中创建与分位数对应的垂直线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我可以创建一个这样的情节:


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.

解决方案

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

这篇关于ggplot2如何在geom_bar图中创建与分位数对应的垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆