【问题标题】:Draw vertical peak lines in histogram using qplot() in R使用 R 中的 qplot() 在直方图中绘制垂直峰值线
【发布时间】:2015-11-01 05:12:09
【问题描述】:

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

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

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

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

我想在这个直方图中画一条峰值线并找出它的值。我在这里探讨了几个问题,但没有一个与 qplot 一起工作。谁能建议我如何在直方图的峰值处画线。

【问题讨论】:

  • 我认为您需要定义“峰值”线的含义。在这个例子中,行在哪里?
  • 横线?垂线?其他线路?无论如何,简单的答案是将您的数据转换为您想要绘制的内容,然后绘制而不是依赖 ggplot(这是一个恰好进行一些基本转换的绘图包)来进行数据整形。跨度>
  • 我只想在有峰值的地方绘制一条垂直线(对应于y轴)。 @Gregor 你能给我举个例子吗,这会很有帮助。
  • 在这个图中,垂直线应该出现在我的第二个栏中,因为它具有最高值。
  • 你想只在最高峰有一条垂直线吗?或在每个局部最大值

标签: r ggplot2 histogram


【解决方案1】:

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

【讨论】: