I want to create a grid of density distribution plots, with a dashed vertical line at the mean, for multiple variables I have in a dataset. Using mtcars dataset as an example, the code for a single variable plot would be:
ggplot(mtcars, aes(x = mpg)) + geom_density() + geom_vline(aes(xintercept =
mean(mpg)), linetype = "dashed", size = 0.6)
I am unclear about how I alter this to make it loop over specified variables in my dataset and produce a grid with the plots of each one. It seems like it would involve some combination of adding facet_grid and the "vars" argument but I have tried a number of combinations with no success.
It seems like in all the examples I can find online, facet_grid splits the plots by subsets of a variable, while keeping the same x and y for each plot, but I want to have the plot of x vary in each graph and the y is the density of values.
In trying to solve this, it is also my understanding that the new release of ggplot includes something involving "quasiquotation" which may help solve my problem (https://www.tidyverse.org/articles/2018/07/ggplot2-tidy-evaluation/) but again, I couldn't quite figure out how to apply the examples provided here to my own issue.
Consider reshaping the data into long format than plotting with facets. Here both x and y scales are free since plot differ in magnitude across the columns.
rdf <- reshape(mtcars, varying = names(mtcars), v.names = "value",
times = names(mtcars), timevar = "variable",
new.row.names = 1:1000, direction = "long")
ggplot(rdf, aes(x = value)) + geom_density() +
geom_vline(aes(xintercept = mean(value)), linetype = "dashed", size = 0.6) +
facet_grid(~variable, scales="free")