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()
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()
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()