ggplot2绘图功能

时间:2019-02-19 22:45:15

标签: r variables ggplot2

我想绘制多个密度图。我正在使用3个以上的变量,但这只是一个例子。

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))

我不想像这样写出来。所以我创建了一个函数:

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")

问题是mtcars$var不起作用。它说object 'mpg' not found。当我打电话dp("mpg")时,我希望它返回引导向量mtcars$mpg。同样,当我拨打电话dp("wt")时,我希望mtcars$var返回引导向量mtcars$wt

0 个答案:

没有答案