【问题标题】:reorder dodge bar plots (ggplot2)重新排序闪避条形图(ggplot2)
【发布时间】:2015-11-28 02:02:33
【问题描述】:

我有一个数据框 lot_main,如下所示:

我想制作一个条形图,其中列根据字数重新排序。

library(ggplot2)
library(viridis)
lotr_main %>% ggplot(aes(x = Character, y = wordcount, fill = Film)) + 
geom_bar(stat="identity",position = "dodge") +
coord_flip() +
scale_fill_viridis("Film",discrete = TRUE, option = "C")

我得到的剧情:

我想要的是每个字符,条是重新排序,顶部最长,底部最短。每个字符的条形顺序不必相同。

【问题讨论】:

  • 欢迎来到 stackoverflow (SO)!如果您制作一个最小的可重现示例来解决您的问题,我们更有可能为您提供帮助。我们可以使用和使用的东西向您展示如何解决您的问题。您可以查看this SO post,了解如何在 R 中制作出色的可重现示例。此外,如果您概述了您已经尝试过的内容,也会有所帮助。

标签: r ggplot2


【解决方案1】:

您本质上是想用一种东西来填充,然后用另一种东西来订购。因此,一种解决方案是将它们分开并创建一个单独的“订单”变量。值得注意的是,我不知道是否按值对条形进行排序,而不是每个“组”具有相同的序列,是否会让你的情节更容易理解.....

创建一些数据:

library(data.table)


set.seed(123)
dat <- expand.grid(group=LETTERS[1:3],
                   subgroup=LETTERS[1:3])
dat$value <- runif(nrow(dat))
setDT(dat)

创建订单变量:

dat[,order:=order(value),by=group]

创建情节

p1 <- ggplot(dat, aes(x=group,y=value, fill=subgroup,group=order))+
  geom_bar(aes(group=order),position="dodge", stat="identity") +
  coord_flip()
p1

【讨论】:

    【解决方案2】:

    这是一个开始。找到数据和灵感here(代码如下)

    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))
    
    
    LoTRdataOrder <- LoTRdata[order(LoTRdata$Words, LoTRdata$Film) , ]
    
    # install.packages("ggplot2", dependencies = TRUE)
    require(ggplot2)
    
    p <- ggplot(LoTRdataOrder, aes(x = Race, y = Words, fill = Film))
    p + geom_bar(stat = "identity", position = "dodge") +
      coord_flip() + guides(fill = guide_legend())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 2021-10-02
      • 2012-09-24
      相关资源
      最近更新 更多