0

When I flip my barchart with coord_flip() I need to reorder the bargraphs, but I don't know how to do that. The solution mentioned here doesn't seem to work on my data, (or I just haven't figured how yet).

This is an example of what I intend to do:

library(ggplot2)

df <- structure(list(vars = c("7. var", "7. var", "7. var", "7. var", 
"1. var", "1. var", "1. var", "1. var", "8. var", "8. var", "8. var", 
"8. var", "4. var", "4. var", "4. var", "4. var"), percentage = c(37, 
22, 41, 1, 4, 12, 49, 35, 13, 34, 30, 24, 1, 11, 32, 56), score = structure(c(1L, 
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("1", 
"2", "3", "4"), class = "factor")), .Names = c("vars", "percentage", 
"score"), row.names = c(NA, 16L), class = "data.frame")

ggplot(df, aes(x = vars, y = percentage, fill = score)) + 
  geom_bar(stat = 'identity', position = 'fill')+
  coord_flip()

As you can see the first bargraph name starts with an eight, and the last one starts with a one. This is not what I intended, it should be the other way around. This is the right order: 1. var, 4. var, 7. var 8. var.

Does anyone know how to do this?

rdatasculptor
  • 8,112
  • 14
  • 56
  • 81

2 Answers2

1

Factoring the vars column works for me

library(ggplot2)

df <- structure(list(vars = c("7. var", "7. var", "7. var", "7. var", 
"1. var", "1. var", "1. var", "1. var", "8. var", "8. var", "8. var", 
"8. var", "4. var", "4. var", "4. var", "4. var"), percentage = c(37, 
22, 41, 1, 4, 12, 49, 35, 13, 34, 30, 24, 1, 11, 32, 56), score = structure(c(1L, 
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("1", 
"2", "3", "4"), class = "factor")), .Names = c("vars", "percentage", 
"score"), row.names = c(NA, 16L), class = "data.frame")

df$vars <- factor(df$vars,levels=unique(sort(df$vars,decreasing=TRUE)))

ggplot(df, aes(x = vars, y = percentage, fill = score)) + 
  geom_bar(stat = 'identity', position = 'fill')+
  coord_flip()
1

If you want to reverse the order of your bars, you can convert them to factor and then reverse the order of the factors.

df$vars <- as.factor(df$vars)
df$vars <- factor(df$vars, levels = rev(levels(df$vars)))

ggplot(df, aes(x = vars, y = percentage, fill = score)) + 
geom_bar(stat = 'identity', position = 'fill') +
coord_flip()

Is that what you are looking for?

Raphael K
  • 2,265
  • 1
  • 16
  • 23