在ggplot中使用aes_string

时间:2018-11-15 11:38:01

标签: r ggplot2

library(dplyr)
library(ggplot2)
library(gridExtra)

df <- data.frame(type = rep(c("cons", "dyn"), each = 15),
                 rain = sample(1:40, 30, replace = T), 
                 tmax =  sample(20:40, 30, replace = T), 
                 tmin = sample(1:10, 30, replace = T))
pdf("plot.pdf")

for(i in 2:ncol(df)){

   variable.name <- names(df)[i] 

    p1 <- ggplot(df, aes_string(variable.name)) + geom_histogram() + facet_wrap(~type)

    # I want to plot `variable.name` of `cons` and `dyn` against each other

    p2 <- ggplot(df, aes_string(x = variable.name[type == "cons"], y = variable.name[type == "dyn"])) + geom_point() 

    grid.arrange(p1, p2)
 }
dev.off()

目前,p2图无法正常工作,这是因为我无法对列进行子集化。

0 个答案:

没有答案