0

I would like to show a simple geom_point, geom_smooth, and geom_abline with helpful legends. Unfortunately, the simple combination of geom_point and geom_smooth places a horizontal line across the point legend, adding geom_abline places a diagonal slash across all legends.

How can I create a simple visual where legend boxes include only a "point", a "line", and a "dashed line"?

Thanks

Examples:

Geom_point and 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, and 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")

Fixed geom_point legend, but slashes remain on other legends

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")

mtcars plot with point, smooth, abline and broken legend

I have looked at these questions but did not understand how to apply to my situation:

eipi10
  • 91,525
  • 24
  • 209
  • 285
nko_jd
  • 43
  • 4

2 Answers2

0

To me, the easiest way to get around this is to simply not list everything as color. You can use size, shape, alpha, etc. to break up the legend.

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")

AndS.
  • 7,748
  • 2
  • 12
  • 17
0

My guess: you are using color for both geom_point and geom_smooth, so the legend attempts to combine both geoms. When you use a different aes, the legend takes them as separate 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 = "") 

Hope it helps!

Chuck Ramirez
  • 245
  • 1
  • 12