如何在tmap中设置常量手动调色板

时间:2018-03-10 18:06:15

标签: r tmap

下面的代码显示了我的问题

library(rgdal)
library(RColorBrewer)
library(tmap)
library(maptools)
data(Europe)
first <- c("a", "a", "a", "d", "d", "d", "c", "c", "c", "c")
second <- c("c", "c", "c", "d", "d", "d", "d", "e", "e", "e")
kod <- c("POL", "DEU", "ESP", "FRA", "CZE", "SVK", "GBR", "ITA", "UKR", "RUS")
nazwy <- data.frame(first, second, kod)
Europe_nazwy <- merge(Europe, nazwy, by.x="iso_a3",by.y="kod")
tm1 <- tm_shape(Europe_nazwy) +  tm_polygons("first", palette="Set1") +
tm_text("first", size="AREA", root=5) +  tm_layout(frame=F, legend.outside = TRUE)
tm2 <- tm_shape(Europe_nazwy) +  tm_polygons("second", palette="Set1") + 
tm_text("second", size="AREA", root=5) +  tm_layout(frame=F, legend.outside = TRUE)
tmap_arrange(tm1, tm2, asp = NA)

它会产生两张地图。我想要的是两个地图上的相同类别都有相同的颜色(就像两个地图上的c都是蓝色而两个地图上的d都是红色的,目前还没有)。有什么建议? 我已经尝试过ggplot2的解决方案(下面的代码),但它没有用。我猜scale_colour_manual在tmaps中不起作用?

library(ggplot2)
kolory <- c("a", "b", "c", "d", "e")
myColors <- brewer.pal(5,"Set3")
names(myColors) <- levels(kolory)
colScale <- scale_colour_manual(name = kolory,values = myColors)

tm1 <- tm_shape(Europe_nazwy) +  tm_polygons("first") + 
tm_text("first", size="AREA", root=5) + 
tm_layout(frame=F, legend.outside = TRUE) + colScale

tm2 <- tm_shape(Europe_nazwy) +  tm_polygons("second") + 
tm_text("second", size="AREA", root=5) + 
tm_layout(frame=F, legend.outside = TRUE) + colScale
tmap_arrange(tm1, tm2, asp = NA)

1 个答案:

答案 0 :(得分:1)

好的,等我的帮助,我想我自己找到了一个可能的解决方案。我所要做的就是为每个地图定义颜色苍白(palete1&amp; palete2),同时铭记值按字母顺序分配颜色。

library(rgdal)
library(RColorBrewer)
library(tmap)
library(maptools)
data(Europe)

first <- c("a", "a", "a", "d", "d", "d", "c", "c", "c", "c")
paleta1 <- c("red", "green", "blue")
second <- c("c", "c", "c", "d", "d", "d", "d", "e", "e", "e")
paleta2 <- c( "green", "blue", "yellow")
kod <- c("POL", "DEU", "ESP", "FRA", "CZE", "SVK", "GBR", "ITA", "UKR", "RUS")
nazwy <- data.frame(first, second, kod)

Europe_nazwy <- merge(Europe, nazwy, by.x="iso_a3",by.y="kod")

tm1 <- tm_shape(Europe_nazwy) +  tm_polygons("first", palette=paleta1) +
tm_text("first", size="AREA", root=5) +  tm_layout(frame=F, legend.outside = TRUE)

tm2 <- tm_shape(Europe_nazwy) +  tm_polygons("second", palette=paleta2) +
 tm_text("second", size="AREA", root=5) +  tm_layout(frame=F, legend.outside = TRUE)
tmap_arrange(tm1, tm2, asp = NA)