Home > OS >  in ggplot2, how to adjust legend sequence as the bar sequence
in ggplot2, how to adjust legend sequence as the bar sequence

Time:09-29

in ggplot2, how to adjust legend sequence as the bar sequence ? (top to bottom ,want to ajust legend sequence from 'abcd' to 'dcba')

plot_data <- data.frame(cat=c('a','b','c','d'),value=c(1:4))
plot_data %>% ggplot(aes(x='1',y=value,fill=cat)) 
  geom_bar(stat='identity',position = position_stack(reverse=TRUE)) 
  geom_text(aes(label=value),position = position_stack(reverse=TRUE,vjust=0.5))

enter image description here

CodePudding user response:

Similar to position_stack you could reverse the order in the legend via the reverse argument of guide_legend, i.e. do guides(fill = guide_legend(reverse = TRUE)):

library(ggplot2)

plot_data <- data.frame(cat = c("a", "b", "c", "d"), value = c(1:4))
ggplot(plot_data, aes(x = "1", y = value, fill = cat))  
  geom_bar(stat = "identity", position = position_stack(reverse = TRUE))  
  geom_text(aes(label = value), position = position_stack(reverse = TRUE, vjust = 0.5))  
  guides(fill = guide_legend(reverse = TRUE))

  • Related