【问题标题】:ggplot geom_histogram with different colorsggplot geom_histogram 不同颜色
【发布时间】:2020-02-20 15:07:08
【问题描述】:

我想在 R 中使用 ggplot2 包创建直方图,并添加垂直线以显示均值-sd 和均值 + sd。

我正在使用以下代码

iris %>%
  ggplot(aes(Sepal.Length)) + geom_histogram() + theme_bw() +
  geom_vline(xintercept = mean(iris$Sepal.Length) - sd(iris$Sepal.Length), linetype = "dashed") +
  geom_vline(xintercept = mean(iris$Sepal.Length), linetype = "solid") +
  geom_vline(xintercept = mean(iris$Sepal.Length) + sd(iris$Sepal.Length), linetype = "dashed")

完美运行。有什么方法可以为每个组添加不同的颜色吗?

例如,低于均值的分数 - 橙色的 sd 和高于均值 + 红色的 sd 的分数。

先谢谢你了。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你的代码没问题,你只需要在aes里面加上fill=Species就好

    iris %>%
      ggplot(aes(Sepal.Length, fill=Species)) + geom_histogram() + theme_bw() +
      geom_vline(xintercept = mean(iris$Sepal.Length) - sd(iris$Sepal.Length), linetype = "dashed") +
      geom_vline(xintercept = mean(iris$Sepal.Length), linetype = "solid") +
      geom_vline(xintercept = mean(iris$Sepal.Length) + sd(iris$Sepal.Length), linetype = "dashed")
    

    这是你想要的吗?

    更新

    iris$value<-cut(iris$Sepal.Length, c(min(iris$Sepal.Length)-1, mean(iris$Sepal.Length) - sd(iris$Sepal.Length), mean(iris$Sepal.Length) + sd(iris$Sepal.Length), max(iris$Sepal.Length)),
                  labels = c("< Mean - SD","Mean",">  Mean + SD"))
    
    iris %>%
      ggplot(aes(Sepal.Length, fill=value)) + geom_histogram() + theme_bw() +
      geom_vline(xintercept = mean(iris$Sepal.Length) - sd(iris$Sepal.Length), linetype = "dashed") +
      geom_vline(xintercept = mean(iris$Sepal.Length), linetype = "solid") +
      geom_vline(xintercept = mean(iris$Sepal.Length) + sd(iris$Sepal.Length), linetype = "dashed")
    

    【讨论】:

    • 感谢您的建议。这很有用,但是,这不是我正在寻找的所需结果。正如您在上面的示例中看到的,低于 5 (mean-sd) 的值具有三种颜色(红色、蓝色、绿色)。更准确地说,我希望每个类别都具有完全相同的颜色。
    • 谢谢@BappaDas,更新后的代码完美运行。
    猜你喜欢
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    相关资源
    最近更新 更多