Home > Enterprise >  Fixing extra legend for stat_summary with two different itens (mean and median)
Fixing extra legend for stat_summary with two different itens (mean and median)

Time:07-22

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.

CodePudding user response:

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)

  • Related