Home > OS >  How can I re-order my percent stacked barchart in R based on descending stack segment height?
How can I re-order my percent stacked barchart in R based on descending stack segment height?

Time:08-24

I'm trying to order the bars of my percent stacked barchart in R based on descending stack segment height. R automatically sorts my categorical data in alphabetical order (in both the barchart and its legend) but I'd like the data to be ordered so to have the biggest bars (the ones with the greatest stack segment height) on top of the barchart and the smallest at the bottom, in a descending manner. I don't know how to do this because I cannot manually set a specific order with a vector prior to using ggplot2: my dataset is quite big and I need it to be ordered based on total field area (a quantitative variable that changes for every single city I'm considering). Does anyone know hot to help me?

CodePudding user response:

You need to set your categorical variable as an ordered factor. For example, using the iris data, the default is for an alphabetical x-axis:

iris%>%
  ggplot(aes(Species,Petal.Length)) 
  geom_col()

enter image description here

Using fct_reorder (from forecats, included in the tidyverse), you can change a character variable to a factor and give it an order in one step. Here I change the order of the x-axis such that is order by the average sepal width of the petal.

iris%>%
  mutate(Species=fct_reorder(Species,Sepal.Width,mean))%>%
  ggplot(aes(Species,Petal.Length)) 
  geom_col()

enter image description here

CodePudding user response:

st_des_as%>%

mutate(COLTURA=fct_reorder(COLTURA,tot_area),.desc=F)%>%

ggplot(aes(x=" ", y=tot_area, fill=COLTURA)) geom_bar(position= "fill", stat="identity")
facet_grid(~ZONA)
labs(x=NULL, y="landcover (%)")
scale_y_continuous(labels=function(x) paste0(x*100)) scale_fill_manual(name="CROP TYPE",values=colours_as)
theme_classic() theme(legend.key.size = unit (10, "pt")) theme(legend.title = element_text(face="bold")) geom_col()

here are some of my data, as you can see they are numerical values divided by region (ZONA) and crop type (COLTURA)

and here are the first graphs: the first one from the left is correctly sorted while the other three ones are sorted not following their bars' height but rather following the same sorting of the first graph, no matter the dimension of their own bars

  • Related