1

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?

Jaap
  • 81,064
  • 34
  • 182
  • 193

3 Answers3

3

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

MrFlick
  • 195,160
  • 17
  • 277
  • 295
2

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

Jaap
  • 81,064
  • 34
  • 182
  • 193
-1

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.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110