Fahim Ahmad
Fahim Ahmad

Reputation: 35

ggplot geom_histogram with different colors

I want to create histogram with ggplot2 package in R and add vertical lines to show the mean-sd and mean+sd.

I am using below codes

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

It works perfectly. Is there any way to add different color for each group?

For example, scores that are below mean - sd with orange color and score that are above mean + sd with red color.

Thank you in advanced.

Upvotes: 1

Views: 473

Answers (1)

UseR10085
UseR10085

Reputation: 8136

Your code is OK, just you have to add fill=Species within aes like

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 Is this what you want?

Update

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

Upvotes: 1

Related Questions