在直方图中使用qplot()绘制垂直峰值线R

问题描述:

我使用ggplot2附带的菱形数据集并创建价格字段的直方图。你可以加载使用在直方图中使用qplot()绘制垂直峰值线R

install.packages(ggplot2) 
data(diamonds) 

我试图分析我用这条线

qplot(price, data = diamonds, geom = "histogram", col = 'blues') 

enter image description here

我想提请高峰线,其中创建直方图中的峰值数据集这个直方图,并找到什么值。我在这里探讨了几个问题,但没有一个与qplot一起工作。任何人都可以建议如何在直方图的峰值处画线。

+0

我认为你需要定义你的意思是“高峰”线。这个例子中的行会在哪里? – hrbrmstr

+0

水平线?垂线?其他线?无论如何,简单的答案就是将数据转换为您想要绘制的内容,然后绘制而不是依赖ggplot(这是一个恰好会进行一些基本转换的绘图软件包)来进行数据整形。 – Gregor

+0

我只想绘制一个垂直线,只要有一个峰值(对应于y轴)。 @格雷戈你能否给我一个例子,这将是非常有帮助的。 – python

手动方式:您可以使用ggplot_build提取直方图信息。然后找到最大y值,以及直方图中相应条的x位置。

library(ggplot2) 
data(diamonds) 

## The plot as you have it 
q <- qplot(price, data = diamonds, geom = "histogram", col = 'blues') 

## Get the histogram info/the location of the highest peak 
stuff <- ggplot_build(q)[[1]][[1]] 

## x-location of maxium 
x <- mean(unlist(stuff[which.max(stuff$ymax), c("xmin", "xmax")])) 

## draw plot with line 
q + geom_vline(xintercept=x, col="steelblue", lty=2, lwd=2) 

enter image description here

在该位置的y值是

## Get the y-value 
max(stuff$ymax) 
# [1] 13256 

使用stat_bin另一种选择,应该给予同样的结果如上,但它是因为隐变量的比较隐晦。

q + stat_bin(aes(xend=ifelse(..count..==max(..count..), ..x.., NA)), geom="vline", 
      color="steelblue", lwd=2, lty=2)