重新排序闪避条形图(ggplot2) [英] reorder dodge bar plots (ggplot2)

查看:80
本文介绍了重新排序闪避条形图(ggplot2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框lot_main:

I have a data frame lot_main that looks like this:

我想制作条形图,并根据单词数对列进行重新排序.

I want to make a bar plot with columns reorders according to the 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")

我得到的剧情:

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

What I want is for each character, the bars are reorders with the longest on the top and shortest at the bottom. The orders of the bars don't need to be the same for each character.

推荐答案

您本质上是想用一件事来填充,而用另一件事来排序.因此,一种解决方案是将它们撬开并创建单独的"order"变量.值得注意的是,我不知道是否按值对条形进行排序,而不是使每个组"具有相同的顺序,这会使您的绘图更易于理解.....

You essentially want to fill by one thing, and order by another. A solution is thus to pry them apart and create a separate 'order' variable. Of note, I don't know if sorting your bars by value instead of having the same sequence each 'group' makes your plot more understandable.....

创建一些数据:

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

这篇关于重新排序闪避条形图(ggplot2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆