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

如何使用ggplot为柱状图的正负条形设置灰色(正)与红色(负)

解决ggplot柱状图按数值正负设置颜色的问题

我来帮你搞定这个颜色设置需求——把负数值的条形设为红色,正数值的设为灰色。核心思路是通过条件判断映射填充色,再手动指定对应颜色,具体代码和解释如下:

完整代码示例

library(tidyverse)

# 先把你的数据整理成规范数据框(如果还没做的话)
df <- tibble(
  rowname = c("revrepo", "bankrate", "CRR", "Callrate", "WPI", "GDP", "FED", "width", "nse", "usd"),
  repo = c(0.888, 0.402, 0.250, 0.723, 0.049, -0.318, 0.110, 0.209, 0.059, 0.185)
)

# 修改后的绘图代码
df %>% 
  mutate(rowname = factor(rowname, levels = rowname[order(repo)])) %>% 
  ggplot(aes(x = rowname, y = repo, fill = ifelse(repo < 0, "Negative", "Positive"))) +
  geom_bar(stat = "identity") +
  ylab("Correlation with repo") +
  xlab("Independent Variable") +
  # 指定正负对应的颜色
  scale_fill_manual(values = c("Negative" = "red", "Positive" = "gray"),
                    name = "Correlation Sign") +
  # 可选优化:旋转x轴标签避免重叠,提升可读性
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

关键步骤解释

  1. 映射填充色:在ggplot()的aes()参数里加入fill = ifelse(repo < 0, "Negative", "Positive"),这样会自动给每个条形根据repo值的正负分配一个分组标签;
  2. 手动指定颜色:用scale_fill_manual()函数,把"Negative"分组对应红色,"Positive"分组对应灰色,还可以通过name参数自定义图例的标题;
  3. 可选优化:添加theme(axis.text.x = element_text(angle = 45, hjust = 1))可以旋转x轴的变量名,避免标签重叠,让图表更美观;
  4. 隐藏图例(可选):如果不需要显示图例,只需要在代码最后加上guides(fill = "none")即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:26:39