【问题标题】:Assign custom colors to each plot of facet_wrap histograms in R - ggplot为 R 中的 facet_wrap 直方图的每个图分配自定义颜色 - ggplot
【发布时间】:2021-06-21 23:49:47
【问题描述】:

我想在 R 中使用 facet_wrap 根据某个列拆分我的图。这是我从here 复制的一个工作示例:

set.seed(1)
df <- data.frame(age = runif(500, min = 10, max = 100), 
group = rep(c("a", "b", "c", "d", "e"), 100))

#Plotting
ggplot(df, aes(age)) + 
geom_histogram(aes(y = (..count..)), binwidth = 5) +
facet_wrap(~group, ncol = 3) 

这会生成所有图,全部为灰色(如下所示)。但是,我希望每个图都具有特定的颜色。也就是说,它们按 c("green","orange","blue","black","re​​d") 的顺序具有以下颜色。图 (a) 中的所有条形均为绿色,(b) 中的所有条形均为橙色,依此类推。这些颜色与我的其他情节相匹配并保持一致性。 我怎样才能完成这项任务? 谢谢。

【问题讨论】:

  • 只需将fill=group 添加到您的aes() 电话和use a scale_fill_manual()
  • 谢谢。但我需要为每个图分配确切的颜色。不是随机的!
  • 已修复。重新阅读您的问题并发布答案。

标签: r ggplot2 facet-wrap facet-grid


【解决方案1】:
ggplot(df, aes(age)) + 
  geom_histogram(aes(y = (..count..), fill=group), binwidth = 5) +
  facet_wrap(~group, ncol = 3) +
  scale_fill_manual(values=c("green","orange","blue","black", "red"))

【讨论】:

  • 很好,谢谢。刚刚在我的代码中添加了set.seed(1),这样您就可以重现与我相同的情节以防止混淆:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 2014-03-18
  • 2011-02-02
  • 2019-08-22
  • 2017-06-07
相关资源
最近更新 更多