2015-10-14 100 views
1

我有一個由'時間',間隔0-2000乘5(x軸)和'步數'組成的數據框,範圍爲0-200。我正在使用qplot,並且我想在步數的最大值處繪製一個geom_vline。它正在繪製一條線,但在一個非常低的位置我無法弄清楚。代碼如下所示:在y值最大的線圖中添加垂直線?

這是一個相當糟糕的娛樂活動,但它適合無所不能。

set.seed(2) 
a<-seq(from=0,to=1000,by=5) 
b<-sample(seq(from = 0, to = 100), size = 201, replace = TRUE) 
df<-data.frame(a,b) 
max(b) 

qplot(a,b,df, geom='line')+ 
    geom_vline(xintercept=max(df$b),color='red') 

你可以看到max(b)=99,但geom_vline沒有繪製那裏。

enter image description here

+0

@帕斯卡爾也許吧,但這些細微之處都超出了我的那一刻......我只是想要繪製了曲線圖,並相交於x軸的垂直線y值最大的地方。如果這涉及廢除這個代碼,就這樣吧。 –

+2

不乾淨,但做你想做的:'geom_vline(xintercept = a [b == max(b)],color ='red')''。 – 2015-10-14 05:37:43

+0

@Pascal這不是最簡單的,但是有訣竅,我認爲你在之前的文章中的評論澄清了爲什麼我最初的方法不起作用。明天我會嘗試ggplot而不是qplot。謝謝! –

回答

0

的代碼繪製垂直線,其中x等於99,並且在該位置y不是最大值。

geom_vline只能的術語來定義,其中它穿過x軸(xintercept參數),和去正確的做法是要映射的x值承載最大y

ggplot(data=df,aes(x=a,y=b)) + 
    xlab("Time") + scale_x_continuous(limits=c(0,1000),breaks=seq(0,1000,50)) + 
    ylab("Number os steps") + scale_y_continuous(limits=c(0,100),breaks=seq(0,100,50)) + 
    geom_line(size=1.2,color='grey40') + 
    geom_vline(xintercept=a[b == max(b)],color='red') + #as suggested by user3710546 
    geom_hline(yintercept=max(b),color='blue',linetype=2) + 
    theme_bw() + 
    theme(panel.grid.major = element_blank(), 
     panel.grid.minor = element_blank()) 

enter image description here