我想按组画一次和二次回归直线(数据不同).

例如,我制作了一个如下所示的图表.

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组:线性)?

总是非常感谢,

enter image description here

推荐答案

一种方法是按组使用两个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()

结果:

enter image description here

R相关问答推荐

用dDeliverr用第二个表更新一个表

R的法国工作日

在R中,如何创建时间间隔的图表?

有没有方法将琴弦完全捕捉到R中的多边形?

如何根据包含相同值的某些列获取总额

从R中的另一个包扩展S3类的正确方法是什么

基于shiny 应用程序中的日期范围子集xts索引

在R中替换函数中的特定符号

使用case_match()和char数组重新编码值

用相同方法得到不同函数的ROC最优截断值

如何读取CSV的特定列时,给定标题作为向量

如何删除最后一个可操作对象

自定义gggraph,使geom_abline图层仅在沿x轴的特定范围内显示

在带有`R`中的`ggmosaic`的马赛克图中使用图案而不是 colored颜色

如果COLSUM为>;0,则COLNAME为向量

如何在R中改变fviz_pca_biplot中圆的边界线的 colored颜色 ?

变长向量的矢量化和

是否可以将线性模型的p值添加到tbl_summary中

Conditional documentr::R中数据帧的summarize()

在ggplot2图表中通过端点连接点