通过ggplot中的stat_summary设置条件颜色 [英] Setting a conditional color by stat_summary in ggplot

查看:255
本文介绍了通过ggplot中的stat_summary设置条件颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图通过ggplot中的统计汇总函数设置一个条件颜色。我在ggplot中创建了一个手段的条形图,并且想要设置一个条件颜色,如果平均值小于0,则将其设为红色,如果它高于0,则将其设为绿色。

so I'm trying to set a conditional color by a stat summary function in ggplot. I'm creating a bar chart of the means in ggplot, and want to set a conditional color that if the mean value is less than 0, make it red and if it's above 0 make it green.

Name      Value
A         10
A         -5
B         15
B         12
C         -2
C         -4

ggplot(data, aes(x=Name, y=Value, group=Name))+
stat_summary(fun.y="mean", geom="bar")

我知道我需要一个ifelse语句,但我是不知道条件是什么。

I know i'd need an ifelse statement in there, but I'm not sure what the condition would be.

推荐答案

如果您在绘制数据之前使用 ggplot ,对于您的情况,先手动汇总数据,然后使用 geom_bar 应该相当简单:

It would be much easier if you prepare your data for plot before using ggplot, for your case aggregating your data before hand and then using geom_bar should be fairly straightforward:

dataSum <- aggregate(Value ~ Name, data, FUN = 'mean')
ggplot(dataSum, aes(x = Name, y = Value, fill = (Value > 0))) + 
       geom_bar(stat = "identity", position = 'dodge') + 
       scale_fill_manual(labels = c("FALSE" = "Less than zero", "TRUE" = "Above zero"), 
                         values = c('red', 'green')) + 
       theme(legend.title = element_blank())

这篇关于通过ggplot中的stat_summary设置条件颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆