我编写了创建密度图的代码,但是当我尝试将它们与facet_grid结合使用时,我收到了错误消息。
有关可重复的示例,请参阅下面的使用mtcars(base R)
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]
p1 <- 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(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()
p1 + facet_grid(. ~ carb)
Error: Aesthetics must be either length 1 or the same as the data (12): xintercept, colour
如果没有facet_grid,代码将工作并输出以下图: