Home > OS >  Merge ggplot fill and size legend keys
Merge ggplot fill and size legend keys

Time:10-14

library(tidyverse)


dframe <- as.data.frame(Titanic)

dframe |>
  ggplot(aes(Class, Sex)) 
  geom_point(aes(size = Freq, fill = Freq), pch = 21) 
  facet_grid(Survived~Age) 
  theme_bw() 
  labs(x = "Survival Rate",
       y = "Gender")

How to update the legend to something like this: enter image description hereFollowing this post: How to add axis to balloonplot

In words: remove the lower legend and "fill" the upper one with color

CodePudding user response:

This is one way with using guides and guide_legend.

library(ggplot2)


dframe |>
  ggplot(aes(Class, Sex)) 
  geom_point(aes(size = Freq, fill = Freq), pch = 21) 
  guides(fill = guide_legend(reverse = TRUE, override.aes = list(alpha = 1))) 
  guides(size = guide_legend(reverse = TRUE)) 
  facet_grid(Survived~Age) 
  theme_bw() 
  labs(x = "Survival Rate",
       y = "Gender")

Created on 2022-10-13 with reprex v2.0.2

  • Related