ggplot geom_histogram具有不同的颜色

时间:2020-02-20 06:27:17

标签: r ggplot2

我想用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的得分为红色。

谢谢你。

1 个答案:

答案 0 :(得分:1)

您的代码没问题,只是您必须在fill=Species之内添加aes,例如

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")

enter image description here 这就是你想要的吗?

更新

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")

enter image description here