You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot组合直方图中手动指定分组填充颜色

解决方法

要给指定分组设置自定义填充色,只需在ggplot代码中添加scale_fill_manual()函数,手动映射分组与颜色的对应关系即可:

set.seed(1)
x <- rbind(data.frame(data = rnorm(500, -1, 1), group = 'First'),
           data.frame(data = rnorm(500, 1, 1), group = 'Second'))
ggplot(x, aes(data, fill=group)) +
  geom_histogram(alpha = 0.5, aes(y=(100*..count..)/sum(..count..)), color='black', position='identity') +
  scale_fill_manual(values = c(First = "red", Second = "green"))

关键说明

  • scale_fill_manual()的values参数接受一个命名向量,向量的名称对应你的分组名,值对应你想要的颜色(支持颜色英文名如"red"、"green",也支持十六进制颜色码如"#FF0000")。
  • 原代码中的alpha = 0.5会保留颜色的半透明效果,若需要纯色,直接移除该参数即可。

内容的提问来源于stack exchange,提问作者Forklift17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:42:34