ggplot: Order bars in faceted bar chart per facet

后端 未结 4 1795
一向
一向 2020-11-30 10:32

I have a dataframe in R that I want to plot in a faceted ggplot bar chart.

I use this code in ggplot:

ggplot(data_long, aes(x = partei, y = wert, fil         


        
4条回答
  •  感情败类
    2020-11-30 10:50

    No need of additionale packages, you can achieve this with plain ggplot:

    1. create an additionale variable for every row
    2. make it a factor, reorder the levels
    3. change the lables of the plot to the original value

    The complete solution:

    data_long %>% 
      mutate(kat_partei = paste0(kat, '_', partei),
             kat_partei = forcats::fct_reorder(kat_partei, wert)) %>% 
      ggplot(aes(x = kat_partei, y = wert, fill = kat, width=0.75)) + 
      geom_bar(stat = "identity", show.legend = FALSE) +
      scale_x_discrete(name=NULL, labels=function(x) sub('^.*_(.*)$', '\\1', x)) +
      scale_fill_brewer(palette="Set2") +
      coord_flip() +
      facet_wrap(~kat, scales='free_y') +
      labs(y = "Wähleranteil [ % ]") +
      theme_bw() + theme(strip.background  = element_blank(),
                         panel.grid.major = element_line(colour = "grey80"),
                         panel.border = element_blank(),
                         axis.ticks = element_line(size = 0),
                         panel.grid.minor.y = element_blank(),
                         panel.grid.major.y = element_blank())
    

    further hints:

    • use geom_col() instead of geom_bar(stat = "identity")
    • use show.legend argument instead of guides(fill=FALSE)

提交回复
热议问题