ggplot 单值因子从图例中删除斜杠

ggplot single-value factor remove slashes from legend

我想展示一个带有有用图例的简单 geom_pointgeom_smoothgeom_abline。不幸的是,geom_pointgeom_smooth 的简单组合在点图例上放置了一条水平线,添加 geom_abline 在所有图例上放置了一条斜线。

如何创建图例框仅包含 "point"、"line" 和 "dashed line" 的简单视觉对象?

谢谢

示例:

Geom_point 和 geom_smooth

mtcars %>%
  ggplot() +
  geom_point(aes(x = carb, y = mpg, color = "Points")) +
  geom_smooth(aes(x = carb, y = mpg, color = "Trendline")) +
  theme(legend.position="bottom") +
  labs(x = "carb",
    y = "mpg",
    color = "LEGEND")

Geom_point、geom_smooth 和 geom_abline

mtcars %>%
  ggplot() +
  geom_point(aes(x = carb, y = mpg, color = "Points")) +
  geom_smooth(aes(x = carb, y = mpg, color = "Trendline")) +
  geom_abline(aes(slope = 1, intercept = 10, color = "ZCustom"), linetype = "dashed") +
  theme(legend.position="bottom") +
  labs(x = "carb",
    y = "mpg",
    color = "LEGEND")

修复了 geom_point 图例,但其他图例仍保留斜线

mtcars %>%
  ggplot() +
  geom_point(aes(x = carb, y = mpg, color = "Points")) +
  geom_smooth(aes(x = carb, y = mpg, color = "Trendline")) +
  geom_abline(aes(slope = 1, intercept = 10, color = "ZCustom"), linetype = "dashed") +
  scale_color_manual(values = c("red", "blue", "black"),
                 label = c("Points", "Trendline", "Custom"),
                 guide = guide_legend(override.aes = list(
                   linetype = c("blank", "solid", "dashed"),
                   shape = c(16, NA, NA)))) +
  theme(legend.position="bottom") +
  labs(x = "carb",
    y = "mpg",
    color = "LEGEND")

我看过这些问题,但不明白如何应用到我的情况:

对我来说,解决这个问题的最简单方法就是不要将所有内容都列为 color。可以使用sizeshapealpha等打散图例

mtcars %>%
  ggplot() +
  geom_point(aes(x = carb, y = mpg, shape = "")) +
  geom_smooth(aes(x = carb, y = mpg, alpha = "")) +
  geom_abline(aes(slope = 1, intercept = 10, color = ""), linetype = "dashed") +
  theme(legend.position="bottom") +
  labs(x = "carb",
    y = "mpg",
    shape = "Points",
    alpha = "Trendline",
    color = "ZCustom")

我的猜测:您对 geom_pointgeom_smooth 都使用了 color,因此图例试图将两个 geom 结合起来。 当您使用不同的 aes 时,图例会将它们视为单独的 attribute/layers.

mtcars %>%
  ggplot( aes(x = carb, y = mpg) ) + 
  geom_point( aes(fill = "Points") ) +    # use 'fill' rather than 'color'
  geom_smooth( aes(color = "Trendline")  ) +
  theme(legend.position = "bottom") +
  labs(x = "carb", y = "mpg", color = "", fill = "") 

希望对您有所帮助!