Home > OS >  Limit the number of keys shown in legend ggplot2
Limit the number of keys shown in legend ggplot2

Time:09-17

Since the ggplot2 version 3.3.5 update, setting breaks to an arbitrary number to limit the number of keys displayed in the legend does no longer work and set the missing breaks to the new NA = gray default instead:

df_Test <- tibble(Year = rep(c("2019", "2020", "2021"), each = 3),
                  Size = c(20, 30, 25, 24, 20, 30, 35, 24, 20),
                  Color_Index = fct_relevel(as.factor(1 : 9))
)

Color_Scale <- c("#dce6f2", "#4f81bd", "#254061", "#4f81bd", "#254061", "#dce6f2", "#254061", "#dce6f2", "#4f81bd")

ggplot(data = df_Test, mapping = aes(x = Year, y = Size, fill = Color_Index, order = Color_Index))  
  geom_bar(stat = "identity")  
  geom_text(mapping = aes(label = Size, group = Color_Index),
            position = position_stack(vjust = 0.5), size = 6, stat = "identity")  
  scale_fill_manual(values = Color_Scale,
                    breaks = c("1","2","3"),
                    labels = c("","",""))   
  guides(fill = guide_legend(title = "Cohorts"))
     

Does anyone know how I can limit the number of legend keys shown in the new version?

Thanks in advance!

CodePudding user response:

You have to name the values. But I'm not sure this is what you want:

ggplot(data = df_Test, mapping = aes(x = Year, y = Size, fill = Color_Index, order = Color_Index))  
  geom_bar(stat = "identity")  
  geom_text(mapping = aes(label = Size, group = Color_Index),
            position = position_stack(vjust = 0.5), size = 6, stat = "identity")  
  scale_fill_manual(
    values = setNames(Color_Scale[1:3], as.character(1:3)),
    breaks = c("1","2","3"),
    labels = c("","",""),
    na.value = "yellow")   
  guides(fill = guide_legend(title = "Cohorts"))

enter image description here

  • Related