如何使用ggplot对条形图中的正负条进行颜色编码

9

我有以下数据:

df
    rowname   repo
1   revrepo  0.888
2  bankrate  0.402
3       CRR  0.250
4  Callrate  0.723
5       WPI  0.049
6       GDP -0.318
7       FED  0.110
8     width  0.209
9       nse  0.059
10      usd  0.185

我正在绘制下面显示的条形图:

df %>% mutate(rowname = factor(rowname, levels = rowname[order(repo)])) %>%
ggplot(aes(x = rowname, y = repo)) +
geom_bar(stat = "identity") +
ylab("Correlation with repo") +
xlab("Independent Variable")

我得到了以下的图表: ggplot bar plot 我希望将所有负数柱子颜色设为红色,所有正数柱子颜色设为灰色。

15
geom_bar(aes(fill = repo < 0), stat = "identity") + scale_fill_manual(guide = FALSE, breaks = c(TRUE, FALSE), values=c("gray", "red")) - Andrey Kolyadin
太棒了。像魔法一样运行! - Nishant
1个回答

4

将Andrey Kolyadin的评论作为解决方案,以使其不再出现为未回答的问题:

geom_bar(aes(fill = repo < 0), stat = "identity") + scale_fill_manual(guide = FALSE, breaks = c(TRUE, FALSE), values=c("gray", "red"))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接