for(i in xxx)ggplot问题

And*_*eas 0 r ggplot2

这很奇怪 - 我想?

library(ggplot2)
tf <- which(sapply(diamonds, is.factor))
diamonds.tf <- diamonds[,tf]
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.但接下来是麻烦:

pl.f <- ggplot(diamonds.tf, aes(x=diamonds.tf[,i]))+
geom_bar()+
xlab(names(diamonds.tf[i]))

for (i in 1:ncol(diamonds.tf)) {
ggsave(paste("plot.f",i,".png",sep=""), plot=pl.f, height=3.5, width=5.5)
}
Run Code Online (Sandbox Code Playgroud)

这会将图保存在我的工作目录中 - 但是使用了错误的x标签.我认为这很奇怪,因为直接调用ggplot会产生正确的情节:

i <- 2
ggplot(diamonds, aes(x=diamonds[,i]))+geom_bar()+xlab(names(diamonds)[i])
Run Code Online (Sandbox Code Playgroud)

我真的不知道如何将其描述为一个合适的标题 - 关于更具描述性的问题标题的建议是最受欢迎的.

提前致谢

Leo*_*yev 6

这并不奇怪 - 你的pl.f不i作为参数.事实上,如果你没有定义i,你甚至无法运行你的代码.我想你想要的东西

pl.f <- function(i)
   ggplot(diamonds.tf, aes(x=diamonds.tf[,i]))+
            geom_bar()+xlab(names(diamonds.tf[i]))

for (i in 1:ncol(diamonds.tf)) {
  p <- pl.f(i)
  ggsave(paste("plot.f",i,".png",sep=""), plot=p, height=3.5, width=5.5)
}
Run Code Online (Sandbox Code Playgroud)

  • 这不是使用aes的好方法 - 你应该传递变量的名称而不是内容.我建议使用`aes_string(x = names(df)[i])` (3认同)