2014-01-06 21 views
1

我有一个回归线,称为“平均值”。 X轴被称为“周”。R ggplot中心的垂直和水平线截距

现在,我想从回归线的每个点绘制垂直和水平线到x轴和y轴。

这里是我的数据:

week mean 
1 0 0 
2 2 0 
3 3 0 
4 4 0 
5 5 0 
6 6 0 
7 7 0 
8 8 8 
9 9 30 
10 10 68 
11 11 121 
12 12 189 
13 13 272 

这里是我的代码:

ggplot()+ 
geom_linerange(data=df2,x=df2$week, ymin=0, ymax=df2$mean, colour="#000000",size=0.1)+ 
geom_hline(data=df2, yintercept=df2[trunc(df2$week==30),"mean"],colour="#000000",size=0.1) 

我已经成功地绘制垂直线,采用geom_linerange

但是,geom_hline只是不会工作。 R只是没有画任何东西。

我不知道,如果geom_hline是我应该使用的函数。我试图使用geom_vline作为垂直线部分,但它从来没有工作,所以我切换回geom_linerange,并且它工作得很完美。

感谢您的任何帮助!

+0

请提供一个可重复的例子。 –

+0

欢迎来到SO,使用dput()提供数据,而不是使用上面的 – Ananta

回答

5

使用geom_segment

DF <- read.table(text=" week mean 
1 0 0 
2 2 0 
3 3 0 
4 4 0 
5 5 0 
6 6 0 
7 7 0 
8 8 8 
9 9 30 
10 10 68 
11 11 121 
12 12 189 
13 13 272", header=TRUE) 


library(ggplot2) 

p <- ggplot(DF, aes(x=week, y=mean)) + 
    geom_segment(aes(xend=week, yend=0), color="blue") + 
    geom_segment(aes(xend=0, yend=mean), color="blue") + 
    geom_line() 

print(p) 

enter image description here