Clara
Clara

Reputation: 23

How to add a second legend for stat_summary point below prop legend in geom_count ggplot?

I have a geom_count plot and add the mean values of the Y-axis (importance) as points using stat_summary. I would like the shape of the point (red rectangle in my case) to be part of the legend so that it is clear that these are the means. How can I get the means symbol to show up in the legend below the prop legend?

#example data:
df <- data.frame(x = c("A", "B", "C", "D", "E"),
                   y = c(1, 2, 3, 4, 5, 5, 4, 3, 2, 1))

#plot
ggplot(df, aes(x = x, y =  y)) +
 geom_count(aes(size= after_stat(prop), group=x)) + 
 theme_bw() +
 scale_size_area(max_size = 8) +
 stat_summary(
   geom = "point",
   fun = "mean",
   col = "black",
   size = 6,
   shape = 23,
   fill = "red",
   show.legend = F) +
 xlab("") +
 ylab("Importance") + 
 scale_y_continuous(labels=c("1" = "Not at all", "2" = "Little ", "3" = "Moderate", "4" = "Quite"  , "5" =  "Very")) +
 theme(axis.text.x = element_text(angle = 30, vjust = 1, hjust=1),
       axis.text.y = element_text(angle =30))  

Click here for plot

Changing to show.legend = T does not solve the problem

I've tried the solution suggested in this previous SO question but could not get it to work in my graph. Using the suggestions of this previous SO question I added the code

  geom_point(aes(shape = "mean"), alpha = 0)+  
  guides(shape=guide_legend(title=NULL, override.aes = list(alpha = 1)))

... which has helped me add a means point to the legend, but I wasn't able to add the right shape (see this plot here)

Upvotes: 2

Views: 413

Answers (1)

Ma&#235;l
Ma&#235;l

Reputation: 52359

Use scale_shape_manual:

df <- data.frame(x = c("A", "B", "C", "D", "E"),
                 y = c(1, 2, 3, 4, 5, 5, 4, 3, 2, 1))

# Plot
ggplot(df, aes(x = x, y =  y)) +
  geom_count(aes(size= after_stat(prop), group=x)) + 
  theme_bw() +
  scale_size_area(max_size = 8) +
  xlab("") +
  ylab("Importance") + 
  scale_y_continuous(labels=c("1" = "Not at all", "2" = "Little ", "3" = "Moderate", "4" = "Quite"  , "5" =  "Very")) +
  theme(axis.text.x = element_text(angle = 30, vjust = 1, hjust=1),
        axis.text.y = element_text(angle =30)) +

  # Stat_summary and legend
  stat_summary(fun = mean, aes(shape = "Mean"), geom = 'point', col = "black", fill = "red", size = 6) +
  scale_shape_manual(values=c("Mean" = 23))

enter image description here

Upvotes: 2

Related Questions