2014-01-06 24 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