ggplot:使用coord_flip反转分组条形图中的条形顺序

p3rjfoxz  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(158)

使用here中的代码,我意识到了一些我不理解的事情:

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

为什么要颠倒条形图的顺序?如何更改条形图的顺序
我知道我可以使用guides(fill = guide_legend(reverse = TRUE)),但是条形图和图例的顺序都颠倒了(图例不再按字母顺序排列)。
question不同,在question中,每个分组条的顺序取决于最高出现次数,我只想知道如何颠倒每个组的顺序(如果不使用coord_flip,顺序也是一样的)。

mwg9r5ms

mwg9r5ms1#

p <- ggplot(LoTRdata, aes(x = Race, y = Words, fill = Film))
p + geom_bar(stat = "identity", position =  position_dodge2(reverse=TRUE)) +
coord_flip()

也许你可以从position_dodge2函数开始

相关问题