Willing to plot multiple barplots on a map, I was able to use this solution below, converting ggplots into images with r magick and putting them on map - also an image.
Any way to plot multiple barplots on a map?
I want to create multiple maps each time, having 10 scenarios, with each 12 barplots to put on the map. I tried implementing a loop, but the image_graph function from magick doesn't work within.
library(ggmap)
library(maps)
library(ggplot2)
library(magick)
mp <- NULL
mapWorld <- borders("world", colour="gray70", fill="gray70")
fig <- image_graph(width = 850, height = 550, res = 96)
ggplot() + mapWorld
dev.off()
df <- data.frame(region = c('France','UK'), name =
c('A','B','C','A','B','C'), value1 = c(20,15,15,10,8,8), value2 =
c(10,15,20,5,8,10) , value3 = c(5,15,10,3,8,5) )
scenarios = c('value1', 'value2', 'value3')
for (scenario in scenarios ) {
for (reg in unique(df$region) ) {
df_reg = df[ (df$region == reg), ]
bp <- ggplot(df_reg, aes_string(x = "region", y = scenario, fill = "name")) +
geom_bar(stat = 'identity') +
theme_bw() +
theme(legend.position = "none", axis.title.x = element_blank(), axis.title.y = element_blank())
barfig <- image_graph(width = 100, height = 75, res = 72)
bp
dev.off()
barplotname = paste0('barfig_',reg )
assign(barplotname, barfig)
}
final <- image_composite(fig, barfig_France, offset = "+75+150")
final <- image_composite(final, barfig_UK, offset = "+325+125")
final
filename = paste0('map_', scenario , ".png")
image_write(final, path = filename, format = "png" )
}
It works properly if I decompose the loop manually as below, and I can't find why it doesn't in the loop. I didn't find info in the magick documentation or examples of uses of the image_graph function within loops.
for (reg in unique(df$region) ) {
df_reg = df[ (df$region == reg), ]
bp <- ggplot(df_reg, aes_string(x = "region", y = "value1")) + geom_bar(stat = 'identity', aes(fill = name) ) + #trying in one
theme_bw() +
theme(legend.position = "none", axis.title.x = element_blank(), axis.title.y = element_blank())
barplotname = paste0('bp_',reg )
assign(barplotname, bp)
}
barfig_France <- image_graph(width = 100, height = 75, res = 72)
bp_France
dev.off()
barfig_UK <- image_graph(width = 100, height = 75, res = 72)
bp_UK
dev.off()
final <- image_composite(fig, barfig_France, offset = "+75+150")
final <- image_composite(final, barfig_UK, offset = "+325+125")
final
If I try to integrate this block in the "for (scenarios... )" loop, issue remains the same, I fail to convert my plots into images