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

Draw vertical peak lines in histogram using qplot() in R

我使用 ggplot2 附带的钻石数据集并创建价格字段的直方图。您可以使用

加载数据集
install.packages(ggplot2)
data(diamonds)

我正在尝试分析我使用这条线创建的直方图中的峰值

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

我想在此直方图中绘制一条峰值线并找出其值。我在这里探讨了几个问题,但 none 正在使用 qplot。谁能建议我如何在直方图的峰值处画线。

手动方式:可以使用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)

该位置的 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)