2

I made a scatter plot of sorts and it has all the information I need: the points from my data, the mean and median for each of my factors on x axis. Now I would like to have a legend that explains what each one is. That is where I'm having trouble.

Plot

I would like the mean to be a red "X" and the median to be a black "X". As you can see, the legend shows the names correctly, but the "X"s are above each other.

Here is my code - should run as is.

library(ggplot2)

ggplot(data = mtcars,
       mapping = aes(x = factor(cyl),
                     y = wt,
                     color = factor(am))) +
  geom_point(size = 3, alpha = 0.7) +
  stat_summary(mapping = aes(shape = "Mean"),
               fun = mean, 
               colour = "red",
               geom = "point",
               size = 4,
               alpha = 0.8) +
  stat_summary(mapping = aes(shape = "Median"),
               fun = median, 
               colour = "black", 
               geom = "point",
               size = 4,
               alpha = 0.8) +
  scale_shape_manual(name = "Stats Measures",
                     limits = c("Mean", "Median"),
                     values=c("x", "x"))

Any help will be appreciated. Thank you in advance, E.

Quinten
  • 35,235
  • 5
  • 20
  • 53

1 Answers1

0

You could change the colors of the shapes in the legend using guide_legend and override.aes of the colour like this:

library(ggplot2)

ggplot(data = mtcars,
       mapping = aes(x = factor(cyl),
                     y = wt,
                     color = factor(am))) +
  geom_point(size = 3, alpha = 0.7) +
  stat_summary(mapping = aes(shape = "Mean"),
               fun = mean, 
               colour = "red",
               geom = "point",
               size = 4,
               alpha = 0.8) +
  stat_summary(mapping = aes(shape = "Median"),
               fun = median, 
               colour = "black", 
               geom = "point",
               size = 4,
               alpha = 0.8) +
  scale_shape_manual(name = "Stats Measures",
                     limits = c("Mean", "Median"),
                     values=c("x", "x")) +
  guides(shape = guide_legend(override.aes = list(colour = c("red","black"))))

Created on 2022-07-21 by the reprex package (v2.0.1)

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • 1
    This is perfect! I saw guide_legend on this other answer, but didn't think it would work for this problem. https://stackoverflow.com/a/52745072/19595193 Thank you very much. – EllaineDelano Jul 21 '22 at 15:09