繁体   English   中英

如何使用ggplot循环绘制多个图形

[英]How to make a loop to plot several graphs using ggplot

这是我的数据框:

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)

我从数据框中选择3个变量,分别针对x1绘制3个散点图,并将其存储在字符向量中:

varlist <- c("x2","x4","x5")

所以我想创建一个函数,使用ggplotggplot与x2,x1与x4和x1与x5的3个独立散点图,其中xxyy是要绘制的不同变量对:

ggplot(data = df) +
  geom_point(mapping = aes(x = xx, y = yy)) +
  geom_smooth(mapping = aes(x = xx, y = yy))

您可以这样做:

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"))

注意:我使用df <- data.frame(x1,x2,x3,x4,x5)而不是df <- c(x1,x2,x3,x4,x5)

x设置为x1mapply将在y上循环,其中包含我们要针对x1绘制的不同变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM