ggplot:使用coord_flip在分组的barplot中反转条的顺序 [英] ggplot: reversed order of bars in grouped barplot with coord_flip

查看:128
本文介绍了ggplot:使用coord_flip在分组的barplot中反转条的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么条的顺序颠倒了?以及如何更改条形的顺序

我知道我可以使用 guides(fill = guide_legend(reverse = TRUE)),但随后条形图和图例的顺序都被颠倒了(图例不再按字母顺序排列)

与该问题相反,在这里,每个分组条的顺序取决于在发生率最高的情况下,我只想知道如何反转每个组的顺序(与不使用 coord_flip 时的顺序相同).

解决方案

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

也许您可以开始使用position_dodge2函数

Using the code from here, I have realized something I do not understand:

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

Why is the order of the bars reversed? And how can I change the order of the bars

I am aware that I could use guides(fill = guide_legend(reverse = TRUE)) but then the order of the bars and the legend are both reversed (the legend is not alphabetically ordered anymore).

In contrast to this question, where the order of each grouped bars is depending on the highest occurence, I just want to know how to reverse the order of each group (the same order it would be as if I wouldn't use coord_flip).

解决方案

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

Maybe you could start play with position_dodge2 function

这篇关于ggplot:使用coord_flip在分组的barplot中反转条的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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