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

使用ggplot2叠加散点图:添加齿轮信息的实现问题求助

解决方案

要实现叠加齿轮信息散点层并保留双图例,只需修正代码中的错误并调整图例配置,以下是完整的可运行代码:

library(ggplot2)
data(mtcars)
mtcars$gear   <- factor(mtcars$gear)
mtcars$cyl    <- factor(mtcars$cyl)
transmission <- data.frame(code = c(1, 0), type = c("manual", "automatic"))
mtcars$transmission <- setNames(transmission$type, transmission$code)[as.character(mtcars$am)]
my.formula <- y ~ x

p <- ggplot(data = mtcars, aes(x=hp, y=mpg)) +
  facet_wrap(~transmission, strip.position = "top", scales = "free", nrow = 1) +
  ggtitle("car horsepower (hp) to effiency (mpg) based on cylinder and number of gears for American vs others cars") +
  # 气缸数散点:用形状+颜色区分,大尺寸
  geom_point(size = 6, aes(shape = cyl, color = cyl)) +
  # 齿轮数散点:用形状区分,固定黑色小尺寸(color放在aes外,避免映射)
  geom_point(size = 2, aes(shape = gear), color = "black") +
  # 气缸数颜色配置
  scale_color_manual(
    name = "Number of Cylinders",
    labels = paste(levels(mtcars$cyl), "cylinders"),
    values = c("turquoise", "orange", "red")
  ) +
  # 统一配置所有形状:气缸用实心,齿轮用空心,避免冲突
  scale_shape_manual(
    values = c(
      "4" = 15, "6" = 16, "8" = 17,
      "3" = 1, "4" = 3, "5" = 4
    )
  ) +
  geom_smooth(method="lm", formula = my.formula, se = FALSE, color = "blue") +
  stat_poly_eq(
    formula = my.formula,
    aes(label = paste(after_stat(eq.label), after_stat(rr.label), sep = "~~~")),
    parse = TRUE, size = 4, col = "black"
  ) +
  # 拆分图例,分别设置气缸和齿轮的图例样式
  guides(
    color = guide_legend(
      title = "Number of Cylinders",
      override.aes = list(shape = c(15,16,17), size = 6)
    ),
    shape = guide_legend(
      title = "Number of Gears",
      override.aes = list(color = "black", size = 2),
      breaks = levels(mtcars$gear)
    )
  ) +
  theme(
    panel.spacing = unit(0, "lines"),
    strip.background = element_blank(),
    plot.title = element_text(hjust = 0.5, color = "black", size = 14, face = "bold.italic"),
    strip.placement = "outside"
  )
print(p)

关键修正点:

  1. 颜色映射错误:将第二个geom_point中的color="black"移到aes()外部,因为这是固定颜色,不是变量映射,避免生成无效的颜色图例。
  2. 笔误修正:将levels(mtcars$gears)改为levels(mtcars$gear),匹配数据列名。
  3. 形状冲突解决:用同一个scale_shape_manual统一配置气缸和齿轮的形状(气缸用实心形状15/16/17,齿轮用空心形状1/3/4),避免形状映射冲突。
  4. 图例拆分配置:通过guides()手动拆分两个图例,分别设置气缸图例的形状/尺寸,以及齿轮图例的颜色/尺寸,确保两个图例独立且显示正确。

内容的提问来源于stack exchange,提问作者JamesR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:42:03