我想用Class绘制变量的分布,并添加垂直线,表示每个Class定义的子集的平均值,并按类着色。当我成功按类对颜色分布进行着色时,垂直线显示为灰色。有关可重复的示例,请参阅以下内容:
library(data.table)
library(ggplot2)
library(ggthemes)
data(mtcars)
setDT(mtcars)
mtcars[, am := factor(am, levels = c(1, 0))]
mean_data <- mtcars[, .(mu = mean(hp)), by = am]
ggplot(mtcars, aes(x = hp, fill = am , color = am)) +
geom_histogram(aes(y=..density..), position="identity",alpha = 0.4) + guides(color = FALSE) +
geom_density (alpha = 0.5)+
geom_vline(data = mean_data, xintercept = mean_data$mu, aes(color = as.factor(mean_data$am)), size = 2, alpha = 0.5) +
ggtitle("Hp by am") + scale_fill_discrete(labels=c("am" , "no am")) +
labs(fill = "Transmission") + theme_economist()
此代码呈现以下图:
您的建议将不胜感激。
答案 0 :(得分:2)
您需要在xintercept
来电中加入aes
映射,以便ggplot
正确映射所有美学:
ggplot(mtcars, aes(x = hp, fill = am , color = am)) +
geom_histogram(aes(y=..density..), position="identity",alpha = 0.4) + guides(color = FALSE) +
geom_density (alpha = 0.5)+
geom_vline(data = mean_data, aes(xintercept = mu, color = as.factor(am)), size = 2, alpha = 0.5) +
ggtitle("Hp by am") + scale_fill_discrete(labels=c("am" , "no am")) +
labs(fill = "Transmission") + theme_economist()
geom
来自aes
不在marshmallow_enum
的电话中的任何内容都会被视为一次性价值,而且并未获得应用于其中的所有映射美学。