[英]For loop for multiple ggplots in R
我有这个
Product <- c("X","Y","Z")
Var1 <- runif(3)
Var2 <- rnorm(3)
Var3 <- rnorm(3)
df <- data.frame(Product,Var1,Var3,Var2)
bar.plot <- function(dat,k,p,this) {
mytitle <- paste("Topic:",as.character(this))
ggplot(dat, aes_string(x = substitute(k), y = substitute(p))) +
geom_bar(position = "dodge",stat = "identity",fill="lightblue", colour="black") +
theme(plot.title=element_text(size=25,face="bold"), axis.text.y = element_text(size=20),axis.title.y = element_blank(),axis.text.x = element_text(size = 10,angle = 30, hjust = 1)) +
labs(title=mytitle)
}
我希望以下代码为df
每个列返回三个图。 虽然没有。
col <- c(Var1,Var2,Var3)
for(i in col){
bar.plot(df,Product,i,"Data")
}
任何想法为什么会这样? 谢谢。
正如@DrDom所说,您需要在col
字符,如果要查看图表,则需要在for循环中print
它们。 (或保存它们,或将它们分配在list
...)
col <- c("Var1", "Var2", "Var3")
for(i in col){
print(bar.plot(df, Product, i, "Data"))
}
虽然这对于您原始的bar.plot
可以正常工作,但完全不需要substitute
(您已经在使用aes_string
!),因此我们可以简化为:
bar.plot <- function(dat,k,p,this) {
mytitle <- paste("Topic:", as.character(this))
ggplot(dat, aes_string(x = k, y = p)) +
geom_bar(position = "dodge", stat = "identity",
fill = "lightblue", colour = "black") +
theme(plot.title=element_text(size = 25, face = "bold"),
axis.text.y = element_text(size = 20),
axis.title.y = element_blank(),
axis.text.x = element_text(size = 10, angle = 30, hjust = 1)) +
labs(title = mytitle)
}
这是一个稍微不同的方法。
bar.plot <- function(dat,k,p,this) {
mytitle <- paste("Topic:",as.character(this))
gg <- data.frame(x=dat[,k],y=dat[,p])
ggplot(gg, aes(x,y)) +
geom_bar(position = "dodge",stat = "identity",fill="lightblue", colour="black") +
theme(plot.title=element_text(size=25,face="bold"), axis.text.y = element_text(size=20),axis.title.y = element_blank(),axis.text.x = element_text(size = 10,angle = 30, hjust = 1)) +
labs(title=mytitle)
}
for(i in 2:4){
print(bar.plot(df,"Product",i,"Data"))
}
这将在函数内部构建带有x
和y
列的数据框,并将其用于ggplot(...)
的调用中,而不是尝试使用aes_string(...)
。
您的代码: col <- c(Var1,Var2,Var3)
创建一个向量长度9,基本上将三个Var列连接在一起。 当for (i in col)
R将i依次设置为col中每个元素的值,因此循环运行9次-而不是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.