我想用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的得分为红色。
谢谢你。
答案 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")
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")