ggplot2直方图中的错误:基于变量的颜色

时间:2016-06-17 17:17:15

标签: r ggplot2 histogram

我正在尝试为具有负值和正值的变量创建直方图,我想根据变量的符号为条形着色,即如果数字为负则为红色,如果数字为正则为绿色。我在ggplot2中使用以下代码:

ggplot(aes(survey_grouped3$difference),data = survey_grouped3)+geom_histogram(binwidth = 10,fill = ifelse(survey_grouped3$difference >= 0,"green","red"))

但是我收到以下错误:

Aesthetics must be either length 1 or the same as the data (26): fill

任何人都可以帮我这个吗?谢谢!

编辑:使用命令

ggplot(survey_grouped3, aes(difference)) +geom_histogram(aes(fill=ifelse(difference > 0,"green","red")), binwidth = 10) +scale_color_identity()

但着色仍然无效。我正在附加我得到的输出。

link to histogram

1 个答案:

答案 0 :(得分:1)

您必须将颜色部分放在aes内,才能从数据中进行映射。此外,您无需在aes内部指定数据框:

ggplot(survey_grouped3, aes(difference)) +
  geom_histogram(aes(fill=ifelse(difference > 0,"green","red")), binwidth = 10) +
  scale_color_identity() # So "red" and "green" actually map to red and green

或者,如果您不打算在剧情中添加任何其他内容:

ggplot(survey_grouped3, aes(difference, fill=ifelse(difference > 0,"green","red"))) +
  geom_histogram(binwidth = 10) +
  scale_color_identity()