You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot绘制GPA-SAT散点图按Tutor_分组配色、加回归线及副标题的方法

修正后可实现需求的完整代码

# 自定义主题补充副标题格式配置
mytheme <- theme(
  legend.position="right", 
  plot.title = element_text(size = 12, hjust = 0.5), 
  plot.subtitle = element_text(size = 10, hjust = 0.5), # 副标题和主标题保持居中对齐
  axis.title = element_text(size = 12)
)

ggplot(data = mydata, mapping = aes(x = GPA, y = SAT, color = as.factor(Tutor_))) + 
  geom_point() + # 继承全局的x、y、颜色映射,无需重复定义
  geom_smooth(method = "lm") + # 继承颜色映射后自动按分组拟合回归线+置信区间
  scale_color_manual(
    name = "Tutor_", # 可自定义图例标题
    values = c("0" = "purple", "1" = "red") # 手动指定分组配色
  ) +
  labs(
    title = "Tutoring: SAT and GPA",
    subtitle = "这里填写你需要的副标题内容" # 主标题下方的副标题在此处设置
  ) +
  mytheme

改动说明

  • 分组配色与图例:将as.factor(Tutor_)映射到color参数后,ggplot会自动生成右侧分类图例,通过scale_color_manual即可精准指定Tutor_=0为紫色、Tutor_=1为红色
  • 分组回归线:颜色映射加入全局aes后,geom_smooth会自动按Tutor_的取值分别拟合线性模型,同时生成对应分组的置信区间
  • 副标题添加:通过labs的subtitle参数设置副标题内容,配合主题中plot.subtitle的格式配置,即可实现副标题在主标题正下方居中显示

内容的提问来源于stack exchange,提问作者B.Nin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:15:04