tags:

views:

147

answers:

1

This is strange - I think?

library(ggplot2)
tf <- which(sapply(diamonds, is.factor))
diamonds.tf <- diamonds[,tf]

So far so good. But next comes the trouble:

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

This saves the plots in my working directory - but with the wrong x-label. I think this is strange since calling ggplot directly produces the right plot:

i <- 2
ggplot(diamonds, aes(x=diamonds[,i]))+geom_bar()+xlab(names(diamonds)[i])

I don't really know how to describe this as a fitting title - suggestions as to a more descriptive question-title is most welcome.

Thanks in advance

+2  A: 

That's not strange -- your pl.f doesn't take i as a parameter. In fact, if you don't define i, you can't even run your code. I think you want something like

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)
}
Leo Alekseyev
This works - and I guess it only goes to show that i have hardly programmed anything at all. It'is funny though, because my original code produced and saved all the right plots. Only the legend was not produced correctly. With your solution everything works.
Andreas
This is not a good way to use aes - you should be passing in the name of the variable not the contents. I'd recommend using `aes_string(x = names(df)[i])`
hadley
I see you give this advice in chapter 10. I Don't think I understand why - but maybe i'll grock it as I start to use ggplot in functions more. Thanks
Andreas