如何根据R中的特定值更改直方图的颜色

时间:2018-03-27 10:37:57

标签: r ggplot2 colors histogram

所以我有这个大数据框,其中包含一个名为“情感”的列,它列出了不同的值,如0,43或0,62等等。

这是df中两个条目的最小示例:

df <- dataframe(text=c("This is awesome", "I hate it"), sentiment=c("0.62","0.43"))

我想使用ggplot 2来绘制直方图。

我的代码如下所示:

ggplot(test)+
aes(x=sentiment, y=..density..,fill=sentiment)+
geom_histogram(binwidth = 0.01)+
geom_vline(aes(xintercept=mean(sentiment)),
         color="blue", linetype="dashed", size=0.5)+
geom_density(alpha=.2,col="#FF6666")

如何为红色下0.5以下的所有“情绪”值和绿色中0.5以上的所有值着色?

谢谢!

1 个答案:

答案 0 :(得分:0)

最简单的方法是在scale_fill_manual的{​​{1}}内使用fill aes()参数:

geom_histogram

enter image description here