конвертируйте ggplots в изображения в пределах al oop, используя rmagick для размещения барплотов на карте - PullRequest
1 голос
/ 27 февраля 2020

Желая построить несколько барплотов на карте, я смог использовать это решение ниже, преобразовав ggplots в изображения с помощью r magick и поместив их на карту - также изображение.

Любой способ нанести на карту несколько барплотов?

Я хочу создавать несколько карт каждый раз, имея 10 сцен ios, с каждыми 12 барплотами, которые нужно поставить на карте. Я попытался реализовать al oop, но функция image_graph от magick не работает внутри.

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" )

    }

Она работает правильно, если я вручную разлагаю l oop, как показано ниже, и не могу найти почему это не в л oop. Я не нашел информации в документации по магии или в примерах использования функции image_graph внутри циклов.

              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

Если я попытаюсь интегрировать этот блок в "for (scenar ios ...)" l oop, проблема останется прежней, я не смог преобразовать свои графики в изображения

1 Ответ

0 голосов
/ 02 марта 2020

Найден обходной путь c, заключающийся в сохранении барплотов и последующем их импорте с использованием image_read

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)) + 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('barfig_',reg, '.svg')

            ggsave(barplotname, bp, width = 1.2, height = 1, dpi = 72)


            plotname = paste0('barfig_', reg)
            img = image_read_svg(barplotname)
            assign(plotname ,img)

          }

    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" )

}
...