I need to plot a stacked rank bar graph, in decreasing order like a sample attached graph. I have also linked my data (data file) that is already ranked for three years - 2018, 2019, and with Existing_Year. I want to keep years on x-axis, and water-use on y-axis, and fill with sectors that can be shown in legend as well with colors.
I am trying this code but not working. I went through various similar questions on this platform but also didn't work.
My code:
rank_use%>%
ggplot(., aes(x = fct_rev(fct_infreq(year)), y = water_use, fill = sectors)) +
geom_bar(position = 'stack', stat = 'identity') +
theme_economist_white() + theme(axis.text.x = element_text(angle = 90), axis.text =
element_text(face= "bold"),legend.position = 'right') +
labs(fill = "Sectors", face="bold")+
ylab('Water Use (Thousand m3)') + xlab("Year")+ ylim(0,50000)+
theme(text=element_text(size=10, family="Arial"))+
ggtitle("Top 10 sectors by water use for 2018, 2019, and with existing year")+
theme(plot.title=element_text( hjust=0.5, vjust=0.5, face='bold'))+
theme(axis.title = element_text(face="bold"))+
theme(axis.title.x = element_text(margin = unit(c(3, 0, 0, 0), "mm")),
axis.title.y = element_text(margin = unit(c(0, 3, 0, 0), "mm")),
plot.title = element_text(vjust = 3))+
theme(legend.title = element_text(colour="black", size=10, face="bold"))
I will appreciate your help with this,
Thanks,
You may set levels of year
before you plot the graph.
Please notice that names of variable from data attatched are slightly different with your code.
library(tidyverse)
library(ggthemes)
rank_ind<- rank_use %>%
group_by(year) %>%
summarize(Water_Use = sum(Water_Use)) %>% arrange(desc(Water_Use)) %>%
pull(year)
rank_use%>%
mutate(year = factor(year, levels = rank_ind)) %>%
ggplot(aes(x = year, y = Water_Use, fill = sector)) +
geom_bar(position = 'stack', stat = 'identity') +
theme_economist_white() + theme(axis.text.x = element_text(angle = 90), axis.text =
element_text(face= "bold"),legend.position = 'right') +
labs(fill = "Sectors", face="bold")+
ylab('Water Use (Thousand m3)') + xlab("Year")+ ylim(0,200000)+ # You should be aware of ylim
theme(text=element_text(size=10, family="Arial"))+
ggtitle("Top 10 sectors by water use for 2018, 2019, and with existing year")+
theme(plot.title=element_text( hjust=0.5, vjust=0.5, face='bold'))+
theme(axis.title = element_text(face="bold"))+
theme(axis.title.x = element_text(margin = unit(c(3, 0, 0, 0), "mm")),
axis.title.y = element_text(margin = unit(c(0, 3, 0, 0), "mm")),
plot.title = element_text(vjust = 3))+
theme(legend.title = element_text(colour="black", size=10, face="bold"))