【问题标题】:How to change color of histogram based on specific values in R如何根据 R 中的特定值更改直方图的颜色
【发布时间】:2018-03-27 10:37:56
【问题描述】:

所以我有这个大数据框,其中包含一个名为“sentiment”的列,其中列出了不同的值,例如 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 的值涂成绿色?

谢谢!

【问题讨论】:

    标签: r ggplot2 colors histogram


    【解决方案1】:

    最简单的方法是在geom_histogramaes() 中使用scale_fill_manualfill 参数:

    ggplot(df)+
      aes(x=sentiment, y=..density..)+
      geom_histogram(binwidth = 0.01, aes(fill = sentiment < .5)) +
      geom_vline(aes(xintercept=mean(sentiment)),
                 color="blue", linetype="dashed", size=0.5)+
      geom_density(alpha=.2,col="#FF6666") +
      scale_fill_manual(values = c("green", "red"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 2020-08-07
      • 2022-01-09
      • 1970-01-01
      • 2019-06-16
      • 2017-04-01
      • 1970-01-01
      相关资源
      最近更新 更多