How to loop to generate graphics in R?

Asked

Viewed 175 times

4

Consider the following Data Frame:

ITENS <-c("A","B","C","D","E")
Q.1 <-c(10,20,10,40,10)
Q.2 <-c(5,25,0,50,10)
Q.3 <-c(15,20,5,40,10)
Q.4 <-c(15,30,5,30,5)
Q.5 <-c(20,25,5,20,15)
Q.6 <-c(10,20,10,40,10)
df <- data.frame(ITENS,Q.1,Q.2,Q.3,Q.4,Q.5,Q.6)

Hence I use the code below to generate a graph:

library(ggplot2)
plot.grafico <- ggplot(data=df, aes(x=df$ITENS, y=df$Q.1)) +
geom_bar(stat="identity") +
xlab("Itens") +
ylab("Quantidade de Alunos") +
ggtitle("Titulo")+ guides(fill=FALSE)
plot.grafico

I mean, it’s a bar graph of the Q.1 column of my data frame.
I would like to make a loop where I could generate the graph of each column.
Currently I do the following:

plot.grafico1 <- ggplot(data=df, aes(x=df$ITENS, y=df$Q.1)) +
geom_bar(stat="identity") +
xlab("Itens") +
ylab("Quantidade de Alunos") +
ggtitle("Titulo")+ guides(fill=FALSE)

plot.grafico2 <- ggplot(data=df, aes(x=df$ITENS, y=df$Q.2)) +
geom_bar(stat="identity") +
xlab("Itens") +
ylab("Quantidade de Alunos") +
ggtitle("Titulo")+ guides(fill=FALSE)

plot.grafico3 <- ggplot(data=df, aes(x=df$ITENS, y=df$Q.3)) +
geom_bar(stat="identity") +
xlab("Itens") +
ylab("Quantidade de Alunos") +
ggtitle("Titulo")+ guides(fill=FALSE)

library(gridExtra)

grid.arrange(plot.grafico1,plot.grafico2,plot.grafico3)

I’d like a routine so I can’t repeat the code six times
Actually my original data frame has 45 columns.

  • The purpose of the site is not to solve exercises but rather to answer programming questions. Try to put what you have already done and what your doubt.

  • 1

    @Phelipe See if it’s clearer after editing. If you can’t help, don’t worry ;)

1 answer

3


I don’t think the loop is the best solution for your case.

# alongue o data frame.
library(tidyr)
long <- df %>% gather(turma, quantidade, Q.1:Q.6)

# use facet_wrap
library(ggplot2)
ggplot(long) + 
  geom_bar(aes(x = ITENS, y = quantidade), stat = "identity") +
  facet_wrap(~turma)

inserir a descrição da imagem aqui

  • I liked it ! Thank you. In fact not using the loop can save on processing time.

Browser other questions tagged

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