ggplot:使用coord_flip在分组的barplot中反转条的顺序 [英] ggplot: reversed order of bars in grouped barplot with coord_flip
问题描述
在
为什么条的顺序颠倒了?以及如何更改条形的顺序
我知道我可以使用 guides(fill = guide_legend(reverse = TRUE))
,但随后条形图和图例的顺序都被颠倒了(图例不再按字母顺序排列)
与该问题相反,在这里,每个分组条的顺序取决于在发生率最高的情况下,我只想知道如何反转每个组的顺序(与不使用 coord_flip
时的顺序相同).
p<-ggplot(LoTRdata,aes(x = Race,y = Words,fill = Film))p + geom_bar(stat ="identity",position = position_dodge2(reverse = TRUE))+coord_flip()
也许您可以开始使用position_dodge2函数
Using the code from here, I have realized something I do not understand:
library(ggplot2)
LoTRdata <- structure(list(Film = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 3L,
3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("The Fellowship Of The Ring",
"The Return Of The King", "The Two Towers"), class = "factor"),
Race = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 1L, 1L, 2L, 2L,
3L, 3L, 1L, 1L, 2L, 2L, 3L, 3L), .Label = c("Elf", "Hobbit",
"Man"), class = "factor"), Gender = structure(c(1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L
), .Label = c("Female", "Male"), class = "factor"), Words = c(1229L,
971L, 14L, 3644L, 0L, 1995L, 331L, 513L, 0L, 2463L, 401L,
3589L, 183L, 510L, 2L, 2673L, 268L, 2459L)), .Names = c("Film",
"Race", "Gender", "Words"), class = "data.frame", row.names = c(NA,
-18L))
p <- ggplot(LoTRdata, aes(x = Race, y = Words, fill = Film))
p + geom_bar(stat = "identity", position = "dodge") +
coord_flip() + guides(fill = guide_legend())
Why is the order of the bars reversed? And how can I change the order of the bars
I am aware that I could use guides(fill = guide_legend(reverse = TRUE))
but then the order of the bars and the legend are both reversed (the legend is not alphabetically ordered anymore).
In contrast to this question, where the order of each grouped bars is depending on the highest occurence, I just want to know how to reverse the order of each group (the same order it would be as if I wouldn't use coord_flip
).
p <- ggplot(LoTRdata, aes(x = Race, y = Words, fill = Film))
p + geom_bar(stat = "identity", position = position_dodge2(reverse=TRUE)) +
coord_flip()
Maybe you could start play with position_dodge2 function
这篇关于ggplot:使用coord_flip在分组的barplot中反转条的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!