【问题标题】:Order in stacked bar with both pos and neg values, ggplot2带有 pos 和 neg 值的堆积条形图,ggplot2
【发布时间】:2021-07-18 19:36:46
【问题描述】:

我的情况似乎不符合之前关于 ggplot2 中堆叠条形内顺序的任何讨论。

我知道堆叠条和图例中两个组件的顺序遵循分配给“fill =”的因子变量的级别。但是我的数据集对于某些级别既有正值,也有其他级别的负值。负值堆积条内的顺序似乎颠倒了级别的顺序。

请允许我用一个例子来说明:

d <- data.frame(
               group=c(rep(1,4),rep(2,4),rep(3,4)),
               category=c(rep(c("male_for","male_against","female_for","female_against"),3)),
               n=c(rep(c(2,-2),6))
               )

d$category <- factor(d$category,c("male_for","female_for","male_against","female_against"))

ggplot(d)+ geom_bar(aes(group,n,fill=category),stat="identity")

click here to see the image (not sure why it doesn't embed. sorry

如您所见,因子变量“类别”中的级别顺序为male_for、female_for、male_against、female_against。传说中的顺序也是如此。但是,我猜由于反对组的负值,图表下半部分的堆叠顺序与因子中定义的水平相反。

谁能找出条形图下半部分仍遵循图例中的顺序(即因子中定义)的解决方案?

非常感谢!

【问题讨论】:

    标签: r ggplot2 stacked-chart


    【解决方案1】:

    颜色是按字母顺序分配的,但您的图例是按因子顺序分配的。由于通常因子顺序是按字母顺序分配的,因此这个问题可能会令人沮丧!

    解决问题的方法不止一种。这是一种方法 - 顺便说一句我使用了geom_col(),因为这正是你在这里使用的……区别?没有stat="identity"

    # I picked viridis, because I like their colors - but any would work
    library(viridis)
    library(tidyverse)
    
    colorPal <- viridis::viridis_pal(end = .8)(4)   # 4 colors; no neon yellow
    
    ggplot(d, aes(group, n, fill = category)) + 
      geom_col() + 
      scale_fill_discrete(type = colorPal,
                          limits = c("male_for",
                                     "female_for",
                                     "male_against",
                                     "female_against"))
    

    【讨论】:

      猜你喜欢
      • 2012-11-23
      • 2019-01-14
      • 1970-01-01
      • 2013-10-14
      • 2021-10-16
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多