重新排序闪避条形图(ggplot2)

时间:2015-11-28 02:02:33

标签: r ggplot2

我有一个数据框lot_main,如下所示:enter image description here

我想根据wordcount创建一个带有列重新排序的条形图。

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

我得到的情节:enter image description here

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

2 个答案:

答案 0 :(得分:3)

你基本上想要填充一件事,然后按另一件事订购。因此,解决方案是将它们分开并创建单独的“订单”变量。值得注意的是,我不知道是否按值排序你的酒吧而不是每个'组'都有相同的序列使你的情节更容易理解......

创建一些数据:

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

enter image description here

答案 1 :(得分:0)

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

LoTRdata

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