Plotting Graphs ggplot inside loop

Asked

Viewed 309 times

3

I’m wanting to create a for using ggplot:

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

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

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?

2 answers

7

The problem is that you’re inside the loop then you have to ask explicitly to print on the chart of ggplot.

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

for(i in 1:6) i

Already 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 thing with the chart of ggplot. For example, the command below does not plot any chart:

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

Already putting the print the 6 graphics appear:

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

0

Guy tries to add a print to his ggplot:

     for(i in 1:6){
    
#print foi adicionado na plotagem do histograma para percorrer os índices

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.