0

I want to plot multiple density plots. I'm working with more than 3 variables but this is just an example.

library(ggplot2)

# mpg density plot
ggplot(mtcars, aes(x=mtcars$mpg)) + geom_density() + xlab("miles/(US) gallon") + ylab("Density") + ggtitle("Density Plot of mtcars$mpg") + theme(plot.title = element_text(hjust = 0.5))

# weight density plot
ggplot(mtcars, aes(x=mtcars$wt)) + geom_density() + xlab("weight (1000 lbs") + ylab("Density") + ggtitle("Density Plot of mtcars$mpg") + theme(plot.title = element_text(hjust = 0.5))

# number of cylinders density plot
ggplot(mtcars, aes(x=mtcars$cyl)) + geom_density() + xlab("number of cylinders") + ylab("Density") + ggtitle("Density Plot of mtcars$mpg") + theme(plot.title = element_text(hjust = 0.5))

I don't want to have to write them out like this. So I created a function:

xlabels <- list("mpg" = "miles/(US) gallon",
            "wt" = "weight (1000 lbs",
            "cyl" = "number of cylinders")

dp<-function(var){
        return(ggplot(mtcars, aes(x=mtcars$var)) + geom_density() + xlab(xlabels$var) 
        + ylab("Density") + ggtitle(paste0("Density Plot of mtcars$", var)) + 
        theme(plot.title = element_text(hjust = 0.5)))
    }

mpg.plot<-dp("mpg")
wt.plot<-dp("wt")
cyl.plot<-dp("cyl")

The problem is mtcars$var doesn't work. It says object 'mpg' not found. When I make a call dp("mpg"), I want it to return the vector mtcars$mpg. Similarly when I make a call dp("wt"), I want mtcars$var to return the vector mtcars$wt.

cooldood3490
  • 2,308
  • 6
  • 48
  • 62

0 Answers0