在密度分布之上绘制中值

Plot median values on top of a density distribution

我正在尝试使用 ggplot2 R 库在密度分布上绘制某些数据的中值。我想将中值作为文本 打印在密度图的顶部 上。

你会通过一个例子明白我的意思(使用 "diamonds" 默认数据框):

我正在打印三个项目:密度图本身、显示每次切割的中值价格的垂直线以及具有该值的文本标签。但是,如您所见,中位数价格在 "y" 轴上重叠(这种美学在 geom_text() 函数中是强制性的)。

有什么方法可以动态地为每个中间价格分配一个"y"值,以便在不同的高度打印它们?例如,在每个 "cut".

的最大密度值处

到目前为止我得到了这个

# input dataframe
dia <- diamonds

# calculate mean values of each numerical variable:
library(plyr)
dia_me <- ddply(dia, .(cut), numcolwise(median))

ggplot(dia, aes(x=price, y=..density.., color = cut, fill = cut), legend=TRUE) +
  labs(title="diamond price per cut") +
  geom_density(alpha = 0.2) +
  geom_vline(data=dia_me, aes(xintercept=price, colour=cut),
             linetype="dashed", size=0.5) +
  scale_x_log10() +
  geom_text(data = dia_me, aes(label = price, y=1, x=price))

(我在 geom_text 函数中为 y 美学分配了一个常量值,因为它是强制性的)

这可能是一个开始(但由于颜色原因,可读性不是很好)。我的想法是在数据中创建一个 'y' 位置,用于绘制中位数线。这有点武断,但我希望 y 位置在 0.2 和 1 之间(以很好地适应情节)。我通过 sequence-command 做到了这一点。然后我试着按中位数价格订购(效果不佳);这是任意的。

#scatter y-pos over plot
dia_me$y_pos <- seq(0.2,1,length.out=nrow(dia_me))[order(dia_me$price,decreasing = T)]


ggplot(dia, aes(x=price, y=..density.., color = cut, fill = cut), legend=TRUE) +
  labs(title="diamond price per cut") +
  geom_density(alpha = 0.2) +
  geom_vline(data=dia_me, aes(xintercept=price, colour=cut),
             linetype="dashed", size=0.5) +
  scale_x_log10() +
  geom_text(data = dia_me, aes(label = price, y=y_pos, x=price))