You could do this, but will still have to call separate plots to view them
Global <- data.frame(country = rep(c("US","JP","LT"), each = 72),
year = "2017",
month = rep(c(1:12), 18),
bincensored = sample(c(0,1), 216, replace = T))
# I am grouping by year here because you have many years in your dataset
df <- Global %>%
group_by(country, year, month) %>%
summarize(blocks = mean(bincensored))
# Just to show how similar this is to what you have been doing, you'll need to filter by year for your dataset for individual country plotting by year, as you've done
df %>% filter(country == "JP") %>%
ggplot(aes(x = month, y = blocks)) +
geom_point() +
geom_line() +
scale_x_continuous(breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
labels = c("Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
pltlist <- list() # a list object to store you plots from loop
# You will need to filter df by year if you are plotting by year. Or alternatively can do that within a loop.
for (i in unique(df$country)) {
plt <- df %>% filter(country == i) %>%
ggplot(aes(x = month, y = blocks)) +
geom_point() +
geom_line() +
scale_x_continuous(breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
labels = c("Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
pltlist[[i]] <- plt
# ggsave(filename = paste0("plt", i,".png"), plt)
}
pltlist[["US"]]
pltlist[["JP"]]
Note that I have only done this using a dummy dataset created for 2017. In your case, if you will want to filter by year. You could save the plots separately, by uncommenting the ggsave()
component
Including year within the loop, to produce country by year plots
This is done from main summary df summarized by all years
for (i in unique(df$country)) {
for(y in unique(df$year)){
plt <- df %>% filter(country == i, year == y) %>%
ggplot(aes(x = month, y = blocks)) +
geom_point() +
geom_line() +
scale_x_continuous(breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
labels = c("Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
pltlist[[paste0(i,y)]] <- plt
# ggsave(filename = paste0("plt", i, y,".png", sep = "_"), plt)}
}