2015-10-14 97 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