【问题标题】:Plot two regression lines (calculated on subset of the same data frame) on the same graph with ggplot使用 ggplot 在同一张图上绘制两条回归线(根据同一数据框的子集计算)
【发布时间】:2013-08-09 16:52:03
【问题描述】:

我有这种数据框:

df<-data.frame(x=c(1,2,3,4,5,6,7,8,9,10),y=c(2,11,24,30,45,65,90,110,126,145), a=c(0.2,0.2,0.3,0.4,0.1,0.8,0.7,0.6,0.8,0.9))

使用 ggplot,我想在同一个图上绘制两条回归线,在条件(a > 或

在视觉上,我想要两条回归线:

df_a<-subset(df, df$a<0.5)

ggplot(df_a,aes(x,y))+ 
  geom_point(aes(color = a), size=3.5) + 
  geom_smooth(method="lm", size=1, color="black") +
  ylim(-5,155) +
  xlim(0,11)

df_b<-subset(df, df$a>0.5)

ggplot(df_b,aes(x,y)) + 
  geom_point(aes(color = a), size=3.5) + 
  geom_smooth(method="lm", size=1, color="black") +
  ylim(-5,155) +
  xlim(0,11)

出现在这个图上:

ggplot(df,aes(x,y))+ geom_point(aes(color = a), size=3.5)

我尝试使用par(new=TRUE) 没有成功。

【问题讨论】:

    标签: r ggplot2 regression


    【解决方案1】:

    制作一个标志变量,并使用组:

    df$small=df$a<0.5
    ggplot(df,aes(x,y,group=small))+geom_point() + stat_smooth(method="lm")
    

    如果你愿意,还可以给自己漂亮的颜色和传奇:

    ggplot(df,aes(x,y,group=small,colour=small))+geom_point() + stat_smooth(method="lm")
    

    或者你想给点上色:

    ggplot(df,aes(x,y,group=small)) + 
       stat_smooth(method="lm")+geom_point(aes(colour=a))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 2017-08-31
      相关资源
      最近更新 更多