如何重新排序ggplot2条形图的条形图?

时间:2016-04-22 12:30:32

标签: r ggplot2

当我用coord_flip()翻转我的条形图时,我需要重新排序条形图,但我不知道该怎么做。提到here的解决方案似乎不适用于我的数据,(或者我还没有想到如何)。

这是我打算做的一个例子:

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()

如您所见,第一个条形图名称以8开头,最后一个以一个开头。这不是我的意图,应该是相反的方式。这是正确的顺序:1。var,4。var,7。var 8. var。

有谁知道怎么做?

2 个答案:

答案 0 :(得分:1)

保理vars列对我有用

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 :(得分:1)

如果您想要反转条形的顺序,可以将它们转换为因子,然后反转因子的顺序。

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()

这是你在找什么?