【问题标题】:How to use the same color scale for points in different maps in R?如何对R中不同地图中的点使用相同的色标?
【发布时间】:2014-01-13 21:08:22
【问题描述】:

我有一个 SpatialPointsDataFrame 类的对象,它看起来像:

            coordinates div score
1   (-86.2905, 32.7131)   1  0.73
2    (-113.17, 34.4462)   2  3.00
3   (-112.769, 35.1567)   4  0.94
4   (-113.193, 33.9167)   5  4.09
5    (-113.265, 34.407)   1  1.50
6   (-113.585, 34.8241)   2  5.98
7   (-113.793, 34.7597)   3  2.55
8   (-113.651, 35.1733)   2  3.21
9   (-113.675, 35.3431)   4  2.83
10   (-113.09, 34.4036)   5  6.07
11  (-114.172, 34.6878)   1  4.56
12  (-120.153, 37.3049)   3  7.00

而我想要的是为每个"div" 类别(仅 5 个)生成一张地图,点颜色随score 列(从 0 到 7 不等)而变化。

我的主要问题是: 如何在不同的地图中使用相同的色标,以便进行比较?

我认为spplot 函数可能完全符合我的要求,但我无法理解该函数的参数是如何工作的。如果这是函数,那么我还有另一个问题,如何绘制点后面的大陆边界? (我正在使用 R 中已经存在的 wrld_simpl 数据)

【问题讨论】:

    标签: r map data-visualization spatial


    【解决方案1】:

    这里是一个 ggplot 的例子:

    library(ggplot2)
    library(maps)
    df$div <- paste("DIV#", df$div)
    ggplot(data=df, aes(x=lon, y=lat)) + 
      geom_polygon(
        data=map_data("state"), 
        aes(x=long, y=lat, group = group),
        colour="white", fill="grey10"
      ) + 
      geom_point(aes(color=score), size=3) +
      facet_wrap(~ div) +
      coord_cartesian(xlim=c(-125, -85), ylim=c(30, 42)) +
      scale_colour_gradient2(
        low="red", mid="yellow", high="green", midpoint=mean(df$score)
      )
    

    我只是快速地将色标拼凑在一起,但情节之间是一致的。请注意,我创建了自己的 data.frame 并带有单独的 lat lon 列。

    【讨论】:

    • 非常感谢!我从未使用过 ggplot2,所以我将不得不对其进行一些研究以了解一切都在做什么。不过解决了我比较急的问题,再次感谢!
    【解决方案2】:

    对于spplot(),您需要使用cuts= 和col.regions= 参数,如下所示:

    library(sp)
    library(gridExtra)          ## For grid.arrange()
    
    ## Example data
    data(meuse)
    coordinates(meuse) <- ~x+y
    range(meuse$copper)         ## Examine range of values to be plotted
    # [1]  14 128
    
    ## Establish intervals and colors to be applied to them
    cuts <- 20*(0:7)
    cols <- blues9[3:9]
    
    ## Show that it works by creating two plots with different data ranges
    ## but same color scale    
    a <- spplot(subset(meuse, copper>40), "copper", cuts=cuts, col.regions=cols)
    b <- spplot(subset(meuse, copper<40), "copper", cuts=cuts, col.regions=cols)
    gridExtra::grid.arrange(a, b, ncol=2)
    

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2018-02-22
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 2016-08-08
      相关资源
      最近更新 更多