[英]How to make a loop to plot several graphs using ggplot
This is my dataframe: 这是我的数据框:
x1 <- c(1,2,3,4)
x2 <- c(3,4,5,6)
x3 <- c(5,6,7,8)
x4 <- c(7,8,9,10)
x5 <- c(8,7,6,5)
df <- c(x1,x2,x3,x4,x5)
I choose 3 variables from my dataframe to plot 3 separate scatterplots each against x1 and store these in a character vector: 我从数据框中选择3个变量,分别针对x1绘制3个散点图,并将其存储在字符向量中:
varlist <- c("x2","x4","x5")
So I want to create a function to make 3 independent scatterplots of x1 with x2, x1 with x4 and x1 with x5, using ggplot
, where xx
and yy
will be the different pairs of variables to plot: 所以我想创建一个函数,使用ggplot
来ggplot
与x2,x1与x4和x1与x5的3个独立散点图,其中xx
和yy
是要绘制的不同变量对:
ggplot(data = df) +
geom_point(mapping = aes(x = xx, y = yy)) +
geom_smooth(mapping = aes(x = xx, y = yy))
You could do: 您可以这样做:
mapply(function(y) print(ggplot(data = df) +
geom_point(aes_string(x = "x1", y = y)) +
geom_smooth(aes_string(x = "x1", y = y))), y=c("x2","x4","x5"))
Note : I used df <- data.frame(x1,x2,x3,x4,x5)
instead of df <- c(x1,x2,x3,x4,x5)
注意:我使用df <- data.frame(x1,x2,x3,x4,x5)
而不是df <- c(x1,x2,x3,x4,x5)
x
is set to x1
, mapply
will loop over y
which contains the different variables we want to have plotted against x1
. x
设置为x1
, mapply
将在y
上循环,其中包含我们要针对x1
绘制的不同变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.