I've created two grouped barplots from the same dataframe, and I'm having the same problem with both. In the first plot, I've grouped data by category (fields in this case) on the x axis, and filled each bar by year, which I've also categorized withfill=as.factor(Year)
. On the second graph I've switched the variables that are visualized on the x axis and the color of the bars (fill). In other words, the data is grouped by year on the x axis, and filled according to field (fill=as.factor(fnum)
). It appears ggplot is ordering the bars based on the y values, but I'm trying to order the data consistenty in categorical, logical way (by year or field). Is there any way to specify order, either in the code for the plots or in the way I structure my dataframe? Thanks.
Code 1:
ggplot(data=OM, aes(factor(fnum), y=Value, fill=as.factor(Year))) +
geom_bar(stat="identity", position = "dodge")+
labs(x='Field', y='Soil Organic Matter %', fill='Year',
title = 'Organic Matter Plotted by Field and Year')+
theme(axis.text.x = element_text(angle=65, vjust=0.6))
Code 2:
ggplot(data=OM, aes(factor(Year), y=Value, fill=as.factor(fnum))) +
geom_bar(stat="identity", position = "dodge",color='black')+
labs(x='Year', y='Soil Organic Matter %', fill='Field',
title = 'Organic Matter Plotted by Field and Year')+
theme(axis.text.x = element_text(angle=65, vjust=0.6))