在r中绘制多条水平线

问题描述 投票:0回答:1

我想绘制多条水平线,每条线在特定点处开始或结束,或者在绘图的两个部分的平均值上具有一条直线。例如,我想在图中显示出这两条红色直线。如何在R中做到这一点?enter image description here


对于两个断点,如何确定下面的方程式?:

BREAK1 = 1962
BREAK2 = 1985
df$grp = ifelse(df$year > BREAK2,"C",if(df$year < BREAK1){"A"}else if (df$year > BREAK1 & df$year < BREAK2){"B"})
r ggplot2
1个回答
1
投票

下面是一种快速的方法。快速背景,如果您适合仅截距的线性模型lm(y〜1),则截距将为均值。因此,您需要定义细分并在此公式中使用geom_smooth,您将得到均线:

library(ggplot2)
set.seed(111)
BREAK = 1985
df = data.frame(year=1960:2020,value=runif(61))
df$grp = ifelse(df$year > BREAK,"B","A")

ggplot(df,aes(x=year,y=value)) + 
geom_line() + geom_point() + 
geom_vline(xintercept=BREAK,linetype="dashed")+
geom_smooth(aes(group=grp),formula=y~1,method="lm",col="red",se=FALSE)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.