facet_grid returns error message in ggplot

2019-08-25 02:02发布

问题:

I have composed code that creates density plots but when I try to combine them with facet_grid I get error messages.

For reproducible examples see bellow using 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

Without facet_grid the code works and outputs the following plot:

标签: r ggplot2 facet