Plotting Graphics ggplot within loop

3

I'm trying to create a for using ggplot:

Carteira<-cbind(A, B, C,D,E,F)

A, B, C, D, E, F are data in the "zoo" format.

My code is:

 for(i in 1:6){

  ggplot(Carteira[,i], aes(Carteira[,i])) + 
  geom_histogram(aes(y =..density..), 
                 breaks=seq(-20, 20, by = 2), 
                 col="black", 
                 fill="blue", 
                 alpha = .1) + 
  geom_density(col=1) + 
  labs(title="Histogram ") +
  labs(x="Returns", y="Count") +
  xlim(c(-20,20))
}

The curious thing is that nothing happens. No error message appears. Where am I going wrong?

    
asked by anonymous 13.09.2015 / 00:13

1 answer

5

The problem is that you are within loop so you have to explicitly ask to print on the ggplot graphic.

For example, in the command below, nothing will appear:

for(i in 1:6) i

If you put print , the numbers appear:

for(i in 1:6) print(i)
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6

It's the same with the ggplot graph. For example, the command below does not plot any graph:

for(i in 1:6) ggplot(mtcars, aes(mpg, cyl)) + geom_point()

Already putting the print the 6 graphs appear:

for(i in 1:6) print(ggplot(mtcars, aes(mpg, cyl)) + geom_point())
    
13.09.2015 / 05:09