Home > Back-end >  how to set the legend for certain axis in ggplot
how to set the legend for certain axis in ggplot

Time:03-16

I have a data like this

df<- structure(list(team_3_F = c("browingal ", "newyorkish", "site", 
"team ", "browingal ", "newyorkish", "site", "team ", "browingal ", 
"newyorkish", "site", "team ", "browingal ", "newyorkish", "site", 
"team "), variable = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("No.T", "AAA_BBB_US", 
"AAA_CCC_US", "AAA_BBB_CCC_US"), class = "factor"), value = c(12, 
4, 6, 22, 0.166666666666667, 0.25, 0, 0.181818181818182, 0.0833333333333333, 
1, 0, 0.0909090909090909, 0.0833333333333333, 0.25, 0, 0.0909090909090909
)), row.names = c(NA, -16L), class = "data.frame")

I am trying to plot it like this

ggplot(df, aes(x = team_3_F, y = variable))  
  stat_summary_2d(
    aes(z = value, fill = after_stat(value)),
    geom = "tile") 
  geom_text(aes(label=round(value,2))) 
  guides(fill=guide_legend(title="Percent"))

How can I guide the legend to only show the trend color for AAA_BBB_US , AAA_BBB_CCC_US , AAA_CCC_US but not for No.T?

CodePudding user response:

You can change the mapping of z inside stat_summary_2d using ifelse, to set the value of z to NA when variable == 'No.T'

ggplot(df, aes(x = team_3_F, y = variable))  
  stat_summary_2d(
    aes(z = ifelse(variable == 'No.T', NA, value), fill = after_stat(value)),
    geom = "tile")  
  geom_text(aes(label = round(value, 2)))  
  guides(fill = guide_legend(title = "Percent"))  
  scale_fill_distiller(palette = "Spectral")  
  coord_equal()  
  theme_minimal()  
  theme(panel.grid = element_blank())

enter image description here

  • Related