1

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

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 但它是自下而上的,我希望与曲线有“一点相交”。

4

1 回答 1

6

这真的或多或少是一样的。我更喜欢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")

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

于 2015-05-06T20:49:14.767 回答