Reputation: 83275
I want to group the bars in a stacked barplot according to the values in another factor-variable. However, I want to do this without using facets.
I want to group the stacked bars according the afk
variable. The normal stacked bar plot can be made with:
ggplot(nl.melt, aes(x=naam, y=perc, fill=stemmen)) +
geom_bar(stat="identity", width=.7) +
scale_x_discrete(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
coord_flip() +
theme_bw()
which gives an alfabetically ordered barplot:
I tried to group them by using x=reorder(naam,afk)
in the aes
. But that didn't work. Also using group=afk
does not have the desired effect.
Any ideas how to do this?
Upvotes: 1
Views: 540
Reputation: 83275
An alternative to @MrFlick's approach (based on the answer @CarlosCinelli linked to) is:
ggplot(nl.melt, aes(x=interaction(naam,afk), y=perc, fill=stemmen)) +
geom_bar(stat="identity", width=.7) +
scale_x_discrete(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
coord_flip() +
theme_bw()
which gives:
Upvotes: 2
Reputation: 206606
reorder
should work but the problem is you're trying to re-order by a factor. You need to be explicit on how you want to use that information. You can either use
nl.melt$naam <- reorder(nl.melt$naam, as.numeric(nl.melt$afk))
or
nl.melt$naam <- reorder(nl.melt$naam, as.character(nl.melt$afk), FUN=min)
depending on whether you want to sort by the existing levels of afk
or if you want to sort alphabetically by the levels of afk
.
After running that and re-running the ggplot code, i get
Upvotes: 3
Reputation: 49670
R tends to see the order of levels as a property of the data rather than a property of the graph. Try reordering the data itself before calling the plotting commands. Try running:
nl.melt$naam <- reorder(nl.melt$naam, nl.melt$afk)
Then run your ggplot
code. Or use other ways of reordering your factor levels in naam
.
Upvotes: -1