Home > Back-end >  Show a legend for each panel in ggplot2?
Show a legend for each panel in ggplot2?

Time:01-25

Given this data:

  mtcars %>%
     gather(-mpg, -hp, key = "var", value = "value") %>% 
  mtcars %>%
  gather(-mpg, -hp, key = "var", value = "value") %>%
  ggplot(aes(x = value, y = mpg, color = hp))  
  geom_point()  
  facet_wrap(~ var, scales = "free")  
  theme_bw()

As you can see, there is one legend for hp (which hide low values). I want a legend for each panel.

CodePudding user response:

As stefan already mentioned in his comment we could use patchwork package:

library(ggplot2)
library(dplyr)
library(patchwork) 


mtcars_list <- mtcars %>%
  gather(-mpg, -hp, key = "var", value = "value") %>% 
  group_split(var)

gg_list = lapply(mtcars_list, function(x) {
  ggplot(x, aes(x = value, y = mpg, color = hp))  
    geom_point()  
    facet_wrap(~ var, scales = "free")  
    theme_bw()
})

# patchwork
wrap_plots(gg_list)

enter image description here

  •  Tags:  
  • Related