Deepansh Arora
Deepansh Arora

Reputation: 742

Putting multiple plots at one page

I generated the plots using for loop but now I'm not able to put all of them on 1 page. My code is:

for (i in seq(2013, 2019, by=1)) { 
  ipl %>%
    filter(season == i) %>% 
    pivot_longer(cols = c(team1, team2), values_to = 'team_name') %>%
    ggplot( aes(x = team_name))+
    geom_bar(stat = "count")+
    ggtitle(paste("Total Number of matches played by each team in ",i, sep=''))+
    coord_flip()+
    scale_y_continuous(breaks = seq(0, 20, 2))+
    labs(x = "Teams", y= "Number of Matches Played")+
    theme(plot.title = element_text(hjust = 0.5, face = "bold"),
          axis.title.x =element_text(hjust = 0.5, size = 16),
          axis.title.y =element_text(hjust = 0.5, size = 16), 
          axis.text.x = element_text(size=13))->g
  print(g)
}

The dataset that I'm working on can be found at kaggle

I'm new to R so any help would be greatly appreciated. Thanks

Upvotes: 0

Views: 39

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You can try using facets for each season :

library(dplyr)
library(ggplot2)

ipl %>%
  filter(between(season, 2013, 2019)) %>%
  tidyr::pivot_longer(cols = c(team1, team2), values_to = 'team_name') %>%
  count(season, team_name) %>%
  ggplot(aes(x = team_name, y = n))+
  geom_col() + 
  coord_flip()+
  scale_y_continuous(breaks = seq(0, 20, 2))+
  labs(x = "Teams", y= "Number of Matches Played")+
  theme(plot.title = element_text(hjust = 0.5, face = "bold"),
        axis.title.x =element_text(hjust = 0.5, size = 10),
        axis.title.y =element_text(hjust = 0.5, size = 16), 
        axis.text.x = element_text(size=13)) + 
  facet_wrap(.~season, scales = 'free_y')

enter image description here

Upvotes: 1

Related Questions