简体   繁体   中英

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

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?

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

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM