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

基于mtcars数据集绘制带分组回归线的彩色散点图求助

解决方案

以下是满足所有需求的改进代码,同时避免了颜色映射冲突的问题:

library(ggplot2)
library(dplyr)

mtcars %>%
  ggplot(aes(x = wt, y = mpg)) +
  # 散点:按vs值填充颜色,使用带填充的点形状
  geom_point(size = 1, shape = 21, aes(fill = factor(vs))) +
  # 回归线:按gear分组绘制,按am值设置线条颜色
  geom_smooth(method = lm, se = FALSE, aes(group = gear, color = factor(am))) +
  # 自定义散点填充色:vs=0为灰色,vs=1为红色
  scale_fill_manual(
    name = "vs",
    values = c("0" = "gray", "1" = "red"),
    labels = c("0" = "vs=0", "1" = "vs=1")
  ) +
  # 自定义回归线颜色:am=0为蓝色,am=1为绿色
  scale_color_manual(
    name = "am",
    values = c("0" = "blue", "1" = "green"),
    labels = c("0" = "am=0", "1" = "am=1")
  ) +
  # 优化图表可读性
  labs(
    x = "Weight (1000 lbs)",
    y = "Miles/(US) gallon",
    title = "MPG vs Vehicle Weight"
  ) +
  theme_minimal()

关键修改说明

  • 散点颜色处理:
    直接用color美学同时映射vs和am会导致颜色冲突,因此改用fill配合带填充的点形状(shape=21),将散点的填充色与回归线的线条颜色拆分为两个独立的美学属性,确保各自的颜色映射互不干扰。

  • 回归线分组与着色:
    在geom_smooth的aes中同时指定group=gear(按gear分组生成3条回归线)和color=factor(am)(按am值为线条着色),再通过scale_color_manual精准指定对应颜色。

  • 数据类型与图例优化:
    将vs和am转换为因子,让图例标签更清晰;同时为两个比例尺添加名称和自定义标签,提升图表的可解释性。

备选方案(需额外包)

如果必须使用color美学为散点着色,可以借助ggnewscale包添加第二个颜色比例尺:

library(ggplot2)
library(dplyr)
library(ggnewscale)

mtcars %>%
  ggplot(aes(x = wt, y = mpg)) +
  geom_point(size = 1, aes(color = factor(vs))) +
  scale_color_manual(
    name = "vs",
    values = c("0" = "gray", "1" = "red"),
    labels = c("0" = "vs=0", "1" = "vs=1")
  ) +
  # 启动新的颜色比例尺
  new_scale_color() +
  geom_smooth(method = lm, se = FALSE, aes(group = gear, color = factor(am))) +
  scale_color_manual(
    name = "am",
    values = c("0" = "blue", "1" = "green"),
    labels = c("0" = "am=0", "1" = "am=1")
  ) +
  labs(x = "Weight (1000 lbs)", y = "Miles/(US) gallon") +
  theme_minimal()

使用此方案前需先安装ggnewscale包:install.packages("ggnewscale")

内容的提问来源于stack exchange,提问作者Ahir Bhairav Orai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:33:19