【问题标题】:How to add a sample vertical line to in a gplot?如何在 gplot 中添加示例垂直线?
【发布时间】:2015-05-06 20:39:12
【问题描述】:

考虑下面这段代码给出的图表:

require(ggplot2)
my_data<-c(70,  71, 75, 78, 78, 79, 80, 81, 84, 85, 87, 87, 90, 91, 95, 95, 96, 96, 97, 98, 98, 100,    101,    102,    102,    102,    102,    104,    104,    104,    107,    107,    109,    110,    110,    110,    111,    112,    113,    113,    114,    115,    118,    118,    118,    120,    124,    131,    137,    137,    139,    145,    158,    160,    162,    165,    169,    177,    179,    180)    


qplot(my_data,dist, geom="line")+xlab("x values")+ylab("Density")+
geom_point()+
ggtitle("cool graph Distribution") + 
geom_line(color="black", size=0.1) +
geom_line(stat = "vline", xintercept = "mean", colour = "red", size=1.1)

结果图如下所示:

我的目标是在图表中添加另一条蓝线:

  1. 与曲线相交
  2. 在 X 轴上显示值
  3. 在上面添加标题

为了可视化它,它应该如下所示:

我知道如何添加 geom_line,但它是自下而上的,我希望与曲线有“一点相交”。

【问题讨论】:

  • 不同意重复:这些答案使用geom_vline,这不适用于这个问题。 (OP 想要一条仅从 y = 0 到分布线的线,而不是一直到图的顶部。)可能还有其他重复项,但上面链接的那个不是很好的匹配。

标签: r graph ggplot2 normal-distribution gplots


【解决方案1】:

其实差不多。对于这样的事情,我更喜欢使用annotate。 (我个人也会用注释来做你的红线。)只需计算你想要的东西去哪里并将它们添加到情节中:

qplot(my_data,dist, geom="line")+xlab("x values")+ylab("Density")+
    geom_point()+
    ggtitle("cool graph Distribution") + 
    geom_line(color="black", size=0.1) +
    geom_line(stat = "vline", xintercept = "mean", colour = "red", size=1.1) +
    annotate(geom = "segment", x = 98, xend = 98, y = 0,
             yend = dnorm(98, mean = mean(my_data), sd = sd(my_data)),
             color = "blue") +
    annotate(geom = "text", x = 98, y = -.02 * max(dist), label = "98")

我将把标题留在顶部作为“读者练习”,根据已经存在的部分,它应该非常简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2019-05-05
    相关资源
    最近更新 更多