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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With