在 R 中,如何为同一面板中的每个组绘制单独的线性和二次回归图?

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

我想每组绘制线性和二次回归线(数据不同)。

例如,我制作如下图。

x=rep(c(0,40,80,120,160),time=2)
y=c(16,21,22,26,35,29,44,72,61,54)
group=rep(c("B","A"),each=5)
dataA=data.frame(x,y,group)
   
ggplot(data=dataA, aes(x=x, y=y))+
  
  stat_smooth(aes(group=group, color=group), 
              method='lm', linetype=1, se=FALSE, 
              formula=y~x, linewidth=0.5) +
  
  geom_point(aes(fill=group, shape=group), color="black", size=4) +
  scale_color_manual(values=c("Dark red","grey15"))+
  scale_fill_manual(values=c("Dark red","grey15"))+
  scale_shape_manual(values=c(24,25))+
  scale_x_continuous(breaks=seq(0,160,40), limits = c(0,160)) +
  scale_y_continuous(breaks=seq(0,80,20), limits = c(0,80)) +
  theme_classic(base_size=20, base_family="serif")+
  theme(legend.position=c(0.89,0.08),
        legend.title=element_blank(),
        legend.key=element_rect(color=alpha("grey",.05), 
                                fill=alpha("grey",.05)),
        legend.background= element_rect(fill=alpha("grey",.05)),
        strip.background = element_rect(color="white", 
                           linewidth=0.5,linetype="solid"),
        axis.line=element_line(linewidth=0.5, colour="black"))+
  windows(width=5.5, height=5)

然后,我觉得A组最好表现二次回归。在这种情况下,如何绘制两个独立的回归图(A组:二次,B组:线性)?

总是非常感谢,

r linear-regression quadratic
1个回答
0
投票

一种方法是使用两个

geom_smooth()
并按组过滤
dataA

library(dplyr)
library(ggplot2)

dataA %>% 
  ggplot(aes(x, y)) + 
  geom_point(aes(color = group)) + 
  geom_smooth(data = filter(dataA, group == "A"), 
              method = "lm", 
              formula = y ~ x + I(x^2), 
              aes(color = group), 
              se = FALSE) + 
  geom_smooth(data = filter(dataA, group == "B"), 
              method = "lm", 
              aes(color = group), 
              se = FALSE) +
  theme_bw()

结果:

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