简体   繁体   English

R ggplot中心的垂直和水平线截距

[英]R ggplot vertical and horizontal line intercept at center

I have a regression line, called "mean". 我有一条回归线,称为“均值”。 X-axis is called "week". X轴称为“周”。

Now, I want to draw vertical and horizontal lines, from each point of the regression line, to x-axis and y-axis. 现在,我想从回归线的每个点到x轴和y轴绘制垂直和水平线。

Here is my data: 这是我的数据:

 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

Here is my code: 这是我的代码:

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)

I have successfully draw the vertical line, using geom_linerange . 我已经使用geom_linerange成功绘制了垂直线。

However, the geom_hline just won't work. 但是, geom_hline不能使用。 R just doesn't draw anything. R只是不画任何东西。

I don't know, if geom_hline is the function I should use. 我不知道,如果geom_hline是我应该使用的功能。 I was trying to use geom_vline for the vertical line part, but it never worked, so I switched back to geom_linerange , and it worked perfectly. 我试图对垂直线部分使用geom_vline ,但是它没有用,所以我切换回geom_linerange ,它可以完美地工作。

Thanks for any help!! 谢谢你的帮助!!

Use geom_segment : 使用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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM