首页 文章

在ggplot2中绘制密度分布之上的中值

提问于
浏览
1

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

你会看到我对一个例子的意思(使用“钻石”默认数据帧):

diamond price per cut

我正在打印三个主题:密度图本身,一条垂直线显示每个切割的中位数价格,以及一个带有该值的文本标签 . 但是,正如您所看到的,中间价格在“y”轴上重叠(这种美学在geom_text()函数中是必需的) .

有没有办法动态地为每个中间价格分配一个“y”值,以便在不同的高度打印它们?例如,在每个“切割”的最大密度值处 .

到目前为止我已经有了这个

# 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美学分配一个常量值,因为它是必需的)

非常感谢提前!

1 回答

  • 4

    这可能是一个开始(但由于颜色不太可读) . 我的想法是在用于绘制中位数线的数据中创建一个“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))
    

    enter image description here

相关问题