How to use the same color scale for points in different maps in R?

自作多情 提交于 2019-12-12 14:34:18

问题


I have an object of the class SpatialPointsDataFrame which looks like:

            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

and what I want is to produce one map for each "div" category (just 5) with the points colors varying with the score column (that varies from 0 to 7).

My main problem is: How to use the same color scale in the different maps so I can compare them?

I figure that the spplot function may do exactly what I want, but I couldn't understand how the arguments of this function work. If this is the function then I have another question, how to plot the borders of the continents behind the points? (I am using the wrld_simpl data that is already in R)


回答1:


Here is an example with 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)
  )

I just threw the color scale together quickly, but it is consistent between plots. Note I created my own data.frame with separate lat lon columns.




回答2:


With spplot(), you'll want to use the cuts= and col.regions= arguments, like this:

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)



来源:https://stackoverflow.com/questions/21101382/how-to-use-the-same-color-scale-for-points-in-different-maps-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!