如何循环访问列名并为每个列创建一个ggplot散点图 [英] How do I loop through column names and make a ggplot scatteplot for each one
问题描述
我有一个dataframe filter
,它是dataframe df2
的一个子集,它由dyplr的 mutate()
函数。
我想遍历一些列并使用它们绘制散点图。
My loop:
colNames< - names(filter)[9:47]
for(i in colNames){
ggplot(filter,aes(x = i,y = CrimesPer10k))+
geom_point(color =#B20000,size = 4,alpha = 0.5 )+
geom_hline(yintercept = 0,size = 0.06,color =black)+
geom_smooth(method = lm,alpha = 0.25,color =black,fill =black)
}
然而我没有输出,也没有任何错误。
我做错了什么?
您需要明确 print ()
由 ggplot()
在中为
循环返回的对象,因为auto- print()
ing会在此处关闭(以及其他一些地方)。
您还需要使用 下面是一个实现这两个例子的示例: aes_string()
代替 aes()
,因为您没有使用 i 作为
过滤器
中的实际变量,但是作为包含过滤器$ c中的变量的字符串
(100)
df < - data.frame Y = Y)
colNames< - names(df)[1:3]
for(i in colNames){
plt< - ggplot(df,aes_string(x = i, y = Y))+
geom_point(color =#B20000,size = 4,alpha = 0.5)+
geom_hline(yintercept = 0,size = 0.06,color =black)+
geom_smooth(method = lm,alpha = 0.25,color =black,fill =black)
print(plt)
Sys.sleep(2)
}
I have a dataframe filter
, which is a subset of dataframe df2
, which was made with dyplr's mutate()
function.
I want to loop through some columns and make scatterplots with them.
My loop:
colNames <- names(filter)[9:47]
for(i in colNames){
ggplot(filter, aes(x=i, y=CrimesPer10k)) +
geom_point(color="#B20000", size=4, alpha=0.5) +
geom_hline(yintercept=0, size=0.06, color="black") +
geom_smooth(method=lm, alpha=0.25, color="black", fill="black")
}
Yet I get no output, nor any errors.
What am I doing wrong?
You need to explicitly print()
the object returned by ggplot()
in a for
loop because auto-print()
ing is turned off there (and a few other places).
You also need to use aes_string()
in place of aes()
because you aren't using i
as the actual variable in filter
but as a character string containing the variable (in turn) in filter
to be plotted.
Here is an example implementing both of these:
Y <- rnorm(100)
df <- data.frame(A = rnorm(100), B = runif(100), C = rlnorm(100),
Y = Y)
colNames <- names(df)[1:3]
for(i in colNames){
plt <- ggplot(df, aes_string(x=i, y = Y)) +
geom_point(color="#B20000", size=4, alpha=0.5) +
geom_hline(yintercept=0, size=0.06, color="black") +
geom_smooth(method=lm, alpha=0.25, color="black", fill="black")
print(plt)
Sys.sleep(2)
}
这篇关于如何循环访问列名并为每个列创建一个ggplot散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!