【问题标题】:How to set colors for bar plot with multiple layers in R?如何在 R 中为具有多个图层的条形图设置颜色?
【发布时间】:2020-02-03 16:26:21
【问题描述】:

我正在使用 ggplot2 使用以下数据中的三个变量“stage”、“sex”和“total”创建条形图:

    residtraj             sex    stage          perc total
   <chr>                 <fct>  <fct>         <dbl> <int>
 1 born rural live rural female No cancer   0.00725     1
 2 born rural live rural female Early stage 0.02        1
 3 born rural live rural female Late stage  0.0462      3
 4 born rural live rural male   No cancer   0.00625     2
 5 born rural live rural male   Early stage 0.0323      4
 6 born rural live rural male   Late stage  0.0602     13
 7 born rural live urban female No cancer   0.138      19
 8 born rural live urban female Early stage 0.12        6
 9 born rural live urban female Late stage  0.215      14
10 born rural live urban male   No cancer   0.194      62

我的代码为:

plot <- ggplot(data, aes(sex, total, fill=residtraj)) +
  geom_bar(stat="identity", position="dodge") +
  facet_wrap(~stage) +
  geom_text(aes(label=paste(total,"(",percent(perc),")")),
            position=position_dodge(width=1), hjust=0.5, vjust=-1, size=2.5) +
  ylab("count(%)")+ ggtitle("Distribution of residence by sex and stage")

我的问题是,如何根据“residtraj”和“sex”设置不同的颜色? (现在颜色仅根据“residtraj”的值自动分配)

【问题讨论】:

  • 所以你会有 4 种颜色?比如 1 代表农村 + 男性、农村 + 女性等等。
  • 是的,像这样。

标签: r ggplot2


【解决方案1】:

您可以在aes的填充参数中使用interaction加入“residtraj”和“sex”:

library(ggplot2)
ggplot(df, aes(sex, total, fill=interaction(residtraj,sex))) +
  geom_bar(stat="identity", position="dodge") +
  facet_wrap(~stage)

数据

structure(list(Row = 1:10, residtraj = c("bornruralliverural", 
"bornruralliverural", "bornruralliverural", "bornruralliverural", 
"bornruralliverural", "bornruralliverural", "bornruralliveurban", 
"bornruralliveurban", "bornruralliveurban", "bornruralliveurban"
), sex = c("female", "female", "female", "male", "male", "male", 
"female", "female", "female", "male"), stage = c("Nocancer", 
"Earlystage", "Latestage", "Nocancer", "Earlystage", "Latestage", 
"Nocancer", "Earlystage", "Latestage", "Nocancer"), perc = c(0.00725, 
0.02, 0.0462, 0.00625, 0.0323, 0.0602, 0.138, 0.12, 0.215, 0.194
), total = c(1L, 1L, 3L, 2L, 4L, 13L, 19L, 6L, 14L, 62L)), row.names = c(NA, 
-10L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x55efd77ad350>)

【讨论】:

  • 谢谢!这就是我需要的!在这种情况下,我可以再问一个问题吗?在这种情况下是否可以手动设置条的颜色?喜欢使用 scale_fill_manual 吗?
  • 你好,可以看到绿色条占据了整个区块,其中一个层级为零。知道如何解决吗?我只是在想那个。否则没问题,因为 OP 可以忍受它:)
  • @StupidWolf,您是指bornruralliverural.male 的栏吗?我觉得是因为Late Stage和bornruralliveurban.male的组合没有任何价值
  • @user12721567,不客气;)。是的,你可以使用scale_fill_manual(values = ...) 来填充你想要的颜色;)
  • @StupidWolf 嗨,因为我只是发布了我的数据集的一部分。就像 dc37 所说,对于那里显示的示例数据,在该类别中没有观察到,所以它为零。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 2018-01-07
  • 2023-03-24
  • 2018-04-07
相关资源
最近更新 更多