【问题标题】:R: How to create multiple maps (rworldmap) using apply?R:如何使用apply创建多个地图(rworldmap)?
【发布时间】:2015-11-26 19:42:52
【问题描述】:

我想使用 apply 系列创建多个地图(类似于 this 示例)。这是我的代码的一个小示例(~200 行 x 150 列)。 (UN 和 ISO3 是 rworldmap 的代码):

df <- structure(list(BLUE.fruits = c(12803543, 
    3745797, 19947613, 0, 130, 4), BLUE.nuts = c(21563867, 533665, 
    171984, 0, 0, 0), BLUE.veggies = c(92690, 188940, 34910, 0, 0, 
    577), GREEN.fruits = c(3389314, 15773576, 8942278, 0, 814, 87538
    ), GREEN.nuts = c(6399474, 1640804, 464688, 0, 0, 0), GREEN.veggies = c(15508, 
    174504, 149581, 0, 0, 6190), UN = structure(c(4L, 5L, 1L, 6L, 
    2L, 3L), .Label = c("12", "24", "28", "4", "8", "n/a"), class = "factor"), 
    ISO3 = structure(c(1L, 3L, 6L, 4L, 2L, 5L), .Label = c("AFG", 
    "AGO", "ALB", "ASM", "ATG", "DZA"), class = "factor")), .Names = c("BLUE.fruits", "BLUE.nuts", "BLUE.veggies", "GREEN.fruits", "GREEN.nuts", 
    "GREEN.veggies", "UN", "ISO3"), row.names = c(97L, 150L, 159L, 
    167L, 184L, 191L), class = "data.frame")

以及我之前用来绘制一张地图的代码:

library(rworldmap)
mapDevice('x11')
spdf <- joinCountryData2Map(df, joinCode="ISO3", nameJoinColumn="ISO3")     
mapWF <- mapCountryData(spdf, nameColumnToPlot="BLUE.nuts", 
               catMethod="quantiles")

注意:在mapCountryData() 中,我使用了单个列的名称(在本例中为"BLUE.nuts")。我的问题是:有没有办法 apply 这个映射代码为不同的列创建六个不同的映射?要么在一个多面板中使用layout(),要么更好地创建六个不同的图,根据它们的名称保存。想法?提前非常感谢

【问题讨论】:

    标签: r apply rworldmap


    【解决方案1】:

    你很接近。

    添加此项以每列保存一个图。

    #put column names to plot in a vector
    col_names <- names(df)[1:6]
    
    
    lapply(col_names, function(x) {
      #opens device to store pdf
      pdf(paste0(x,'.pdf'))
      #plots map
      mapCountryData(spdf, nameColumnToPlot=x)
      #closes created pdf 
      dev.off()
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      相关资源
      最近更新 更多