在列上循环播放ggplot2 [英] Looping over ggplot2 with columns
问题描述
我试图循环数据框和列以产生多个图。我有一个数据框的列表,对于每个数据框,我想绘制一个对几个预测变量之一的响应。例如,我可以轻松地跨越数据框:
df1 = data.frame(response = rpois(10,1),value1 = rpois(10,1),value2 = rpois(10,1))
df2 = data.frame(response = rpois(10,1),value1 = rpois(10,1),value2 = rpois(10,1))
$ lapply(list(df1,df2),function(i)ggplot(i,aes(y = response,x = value1))+ geom_point())
但是我在跨数据框中的列循环时遇到问题:
我怀疑它与我对待美学的方式有关。
最终,我想将字符串 lapply
一起生成数据框和列的所有组合。
任何帮助表示赞赏!
编辑:乔兰有它!当使用 aes_string
时,必须将非列表响应放在引号中。 lapply(list(value1,value2),function(i)ggplot(df1,aes_string(x = i,y =response))+ geom_point())
作为参考,这里是串接 lapply
函数以产生所有组合:
lapply(list(df1,df2),function(x)
lapply(list(value1,value2),function (i)ggplot(x,aes_string(x = i,y =response))+ geom_point()))
lapply(list(value1,value2),
function( i)ggplot(df1,aes_string(x = i,y =response))+ geom_point())
I am attempting to loop over both data frames and columns to produce multiple plots. I have a list of data frames, and for each, I want to plot the response against one of several predictors.
For example, I can easily loop across data frames:
df1=data.frame(response=rpois(10,1),value1=rpois(10,1),value2=rpois(10,1))
df2=data.frame(response=rpois(10,1),value1=rpois(10,1),value2=rpois(10,1))
#Looping across data frames
lapply(list(df1,df2), function(i) ggplot(i,aes(y=response,x=value1))+geom_point())
But I am having trouble looping across columns within a data frame:
lapply(list("value1","value2"), function(i) ggplot(df1,aes_string(x=i,y=response))+geom_point())
I suspect it has something to do with the way I am treating the aesthetics.
Ultimately I want to string together lapply
to generate all combinations of data frames and columns.
Any help is appreciated!
EDIT: Joran has it! One must put the non-list responses in quotes when using aes_string
lapply(list("value1","value2"), function(i) ggplot(df1,aes_string(x=i,y="response"))+geom_point())
For reference, here is stringing the lapply
functions to generate all combinations:
lapply(list(df1,df2), function(x)
lapply(list("value1","value2"), function(i) ggplot(x,aes_string(x=i,y="response"))+geom_point() ) )
Inside of aes_string()
, all variables need to be represented as character
. Add quotes around "response".
lapply(list("value1","value2"),
function(i) ggplot(df1, aes_string(x=i, y="response")) + geom_point())
这篇关于在列上循环播放ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!