1
votes

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.

my data in long format

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: enter image description here

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?

3
Jaap, for some reason I can´t copy your dputed data, is it correct? It seems that some quotes are missing.Carlos Cinelli
@CarlosCinelli I've updated the question with a link to the data.Jaap
I think this has what you need: stackoverflow.com/questions/20060949/…Carlos Cinelli

3 Answers

3
votes

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

updated bar chart

2
votes

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: enter image description here

-1
votes

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.