r - ggplot: Order bars in faceted bar chart per facet -
i have dataframe in r want plot in faceted ggplot bar chart.
i use code in ggplot:
ggplot(data_long, 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) + 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")
you can see last facet in desired descending order. facets ordered in descending order, meaning label order changes. therefore need facets have own y-axis labels.
this data i'm using:
partei kat wert 1 sp kand1 95.41 2 grüne kand1 80.60 3 al kand1 75.77 4 bdp kand1 54.02 5 glp kand1 47.91 6 cvp kand1 39.01 7 evp kand1 36.20 8 fdp kand1 32.01 9 svp kand1 5.71 10 edu kand1 1.10 11 sp kand2 18.05 12 grüne kand2 7.15 13 al kand2 9.02 14 bdp kand2 62.30 15 glp kand2 39.18 16 cvp kand2 42.41 17 evp kand2 23.14 18 fdp kand2 94.66 19 svp kand2 29.93 20 edu kand2 34.97 21 sp kand3 0.51 22 grüne kand3 0.27 23 al kand3 3.92 24 bdp kand3 9.21 25 glp kand3 2.53 26 cvp kand3 2.70 27 evp kand3 3.52 28 fdp kand3 23.19 29 svp kand3 92.49 30 edu kand3 60.64 31 sp kand4 52.98 32 grüne kand4 81.28 33 al kand4 56.42 34 bdp kand4 7.52 35 glp kand4 13.65 36 cvp kand4 4.06 37 evp kand4 9.96 38 fdp kand4 1.46 39 svp kand4 0.94 40 edu kand4 0.00 41 sp kand5 7.51 42 grüne kand5 9.19 43 al kand5 9.94 44 bdp kand5 25.30 45 glp kand5 69.58 46 cvp kand5 10.59 47 evp kand5 9.23 48 fdp kand5 17.61 49 svp kand5 3.60 50 edu kand5 3.43 51 sp kand6 4.29 52 grüne kand6 2.37 53 al kand6 7.73 54 bdp kand6 13.14 55 glp kand6 11.67 56 cvp kand6 75.43 57 evp kand6 19.34 58 fdp kand6 6.52 59 svp kand6 2.43 60 edu kand6 6.40 61 sp kand7 1.87 62 grüne kand7 2.98 63 al kand7 5.87 64 bdp kand7 6.70 65 glp kand7 1.29 66 cvp kand7 2.73 67 evp kand7 80.91 68 fdp kand7 1.10 69 svp kand7 1.58 70 edu kand7 45.47
because it's easier see code in action, here's solution generates plots inside 1 call lapply. there other issues figure out (ordering, getting colors right) , puzzle.
#create list of plots myplots <- lapply(split(dat,dat$kat), function(x){ #relevel factor partei wert inside subset x$partei <- factor(x$partei, levels=x$partei[order(x$wert,decreasing=f)]) #make plot p <- ggplot(x, aes(x = partei, y = wert, fill = kat, width=0.75)) + geom_bar(stat = "identity") + scale_fill_discrete(drop=f)+ #to force levels considered, , different colors theme_bw()+ theme(legend.position="none")+ labs(y="wähleranteil (%)", x="", title=unique(x$kat))+ coord_flip() }) do.call(grid.arrange,(c(myplots, ncol=3)))
Comments
Post a Comment