Reputation: 332
I have the following command that I would like to draw a histogram in an ordered manner.
So the code is as follows:
ggplot(upstream, aes(x=type, y=round(..count../sum(..count..) * 100, 2))) + geom_histogram(fill= "red", color = "red") + xlab ("Vehicle Type") +
ylab("Percentage of Vehicles in the Category (%)") + ggtitle ("Percentage of Upstream Vehicles by Type") +
stat_bin(geom="text", aes(label=round(..count../sum(..count..) * 100, 2)), vjust=-0.5)
The output is:
I would like to arrange the bars in an ordered manner, so I use reorder()
function in aes
, but this gives me the following problem:
stat_bin requires the following missing aesthetics x
How can I use reorder without getting this error? I couldn't seem to be able to figure it out with the posted solutions.
Thanks for suggestions in advance.
EDIT 1: I fixed what I was looking for based on joran's suggestion with geom_bar() as follows in case anyone needs it:
# Reorder the factor you are trying to plot on the x-side (descending manner)
upstream$type <- with(upstream, reorder(type, type, function(x) -length(x)))
# Plotting
ggplot(upstream, aes(x=type, y=round(..count../sum(..count..) * 100, 2))) + geom_bar(fill= "blue", color = "blue") + xlab ("Vehicle Type") +
ylab("Percentage of Vehicles in the Category (%)") + ggtitle ("Percentage of Upstream Vehicles by Type") +
stat_bin(geom="text", aes(label=round(..count../sum(..count..) * 100, 2)), vjust=-0.5)
Upvotes: 2
Views: 4737
Reputation: 1225
Here is a reproducible example of the behaviour you are looking for. It is copied from FAQ: How to order the (factor) variables in ggplot2
# sample data.
d <- data.frame(Team1=c("Cowboys", "Giants", "Eagles", "Redskins"), Win=c(20, 13, 9, 12))
# basic layer and options
p <- ggplot(d, aes(y=Win))
# default plot (left panel)
# the variables are alphabetically reordered.
p + geom_bar(aes(x=Team1), stat="identity")
# re-order the levels in the order of appearance in the data.frame
d$Team2 <- factor(d$Team1, as.character(d$Team1))
# plot on the re-ordered variables (Team2)
p + geom_bar(aes(x=Team2), data=d, stat="identity")
Upvotes: 2