【问题标题】:ggplot: reversed order of bars in grouped barplot with coord_flipggplot:在带有coord_flip的分组条形图中反转条形顺序
【发布时间】:2023-03-08 02:09:01
【问题描述】:

使用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 相比,每个分组条的顺序取决于最高出现率,我只想知道如何反转每个组的顺序(与我不会的顺序相同)不要使用coord_flip)。

【问题讨论】:

  • 看看this post;即使使用相同的数据,问题似乎也是一样的。
  • 我之前发现了这篇文章,这实际上是我的问题的来源。因为在最后一个答案中,顺序取决于每组条形的最高出现次数。但是,我试图找出使用coord_flip 后如何翻转条形的顺序。
  • aes(x = Race, y = Words, fill = forcats::fct_rev(Film))?
  • 顺便说一句,发生这种情况的原因是,这些组的闪避增加了 x(现在是 y),并且 (0, 0) 在左下角。所以第一组(红色)最接近 0,这是最低的。

标签: r ggplot2


【解决方案1】:
p <- ggplot(LoTRdata, aes(x = Race, y = Words, fill = Film))
p + geom_bar(stat = "identity", position =  position_dodge2(reverse=TRUE)) +
coord_flip() 

也许你可以开始玩 position_dodge2 函数

【讨论】:

  • 在尝试了很多解决方法后,这对我有用。
猜你喜欢
  • 1970-01-01
  • 2018-09-01
  • 2020-10-16
  • 1970-01-01
  • 2018-12-03
  • 2017-07-21
  • 2013-08-12
  • 1970-01-01
相关资源
最近更新 更多