Reputation: 35
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
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")
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")
Upvotes: 1