ggplot: Order bars in faceted bar chart per facet

后端 未结 4 1807
一向
一向 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:40

    using the comments above I came up with this code:

    names <- levels(unique(data_long$kat))
    
    plist <- list()
    plist[]
    
    for (i in 1:length(names)) {
        d <- subset(data_long,kat == names[i])
        d$partei <- factor(d$partei, levels=d[order(d$wert),]$partei)
    
        p1 <- ggplot(d, aes(x = partei, y = wert, fill = kat, width=0.75)) + 
        labs(y = "Wähleranteil [ % ]", x = NULL, fill = NULL) +
        geom_bar(stat = "identity") +
        facet_wrap(~kat) +
        scale_y_continuous(limits=c(0, 100)) +
        coord_flip() +
        guides(fill=FALSE) +
        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() ) +
        theme(legend.position="bottom") +
        scale_fill_brewer(palette="Set2")
    
    
        plist[[names[i]]] = p1
    }   
    
    
    
    do.call("grid.arrange", c(plist, ncol=4)
    

    not as elegant though... but it gives this:

    all nicely ordered descending :-)

提交回复
热议问题