我正在尝试使用挪威的市政数据,而我对QGIS,shapefile并在R中进行绘图完全陌生。我从这里下载市政: Administrative enheter kommuner / Administrative units municipalities
可复制的文件在这里: Joanna's github
我已经下载了QGIS,所以我可以在那里打开GEOJson文件并将其转换为shapefile。我能够做到这一点,并将数据读入R:
library(sf)
test=st_read("C:/municipality_shape.shp")
head(test)
我自己给不同的自治市指定了不同的值/等级(我称之为 faktor ),并将此分类存储在称为 df_new 的数据框中。我希望将此“分类”合并到上面的“测试”对象上,并希望将具有分类属性的地图绘制到地图上:
test33=merge(test, df_new[,c("Kommunekode_str","faktor")],
by=c("Kommunekode_str"), all.x=TRUE)
这可行,但是当我用tmap
绘制时,
library(tmap)
tmap_mode("view")
tm_shape(test33) +
tm_fill(col="faktor", alpha=0.6, n=20, palette=c("wheat3","red3")) +
tm_borders(col="#000000", lwd=0.2)
它引发此错误:
Error in object[-omit, , drop = FALSE] : incorrect number of
dimensions
如果我仅使用基本图,
plot(test33)
我得到图片了
您看到我得到了三个情节。这与我上面的错误有关吗?
答案 0 :(得分:2)
我认为这里的主要问题是,您试图绘制的形状过于复杂,因此tmap
很难加载所有这些数据。 ggplot
也无法加载多边形。
如果您要制作一个Choropleth贴图,您可能不需要那么多的多边形精度,所以我建议您先简化您的多边形。以我的经验,最好的方法是使用软件包rmapshaper
:
# keep = 0.02 will keep just 2% of the points in your polygons.
test_33_simple <- rmapshaper::ms_simplify(test33, keep = 0.02)
我现在可以使用您的代码生成以下内容:
tmap_mode("view")
tm_shape(test_33_simple) +
tm_fill(col="faktor", alpha=0.6, n=20, palette=c("wheat3","red3")) +
tm_borders(col="#000000", lwd=0.2)
这会生成一个交互式地图,并且配色方案不适合区分市政当局之间的差异。
由于您在评论中表示不确定要使用交互式地图还是静态地图,因此我将举一个带有静态地图和一些配色方案的示例。
以下使用classInt
包为您的地图设置中断。流行的中断方案是使用fisher-jenks算法的“ fisher”。确保您研究了各种不同的选择,以选择适合您的情况的选择:
library(ggplot2)
library(dplyr)
library(sf)
library(classInt)
breaks <- classIntervals(test_33_simple$faktor, n = 6, style = 'fisher')
#label breaks
lab_vec <- vector(length = length(breaks$brks)-1)
rounded_breaks <- round(breaks$brks,2)
lab_vec[1] <- paste0('[', rounded_breaks[1],' - ', rounded_breaks[2],']')
for(i in 2:(length(breaks$brks) - 1)){
lab_vec[i] <- paste0('(',rounded_breaks[i], ' - ', rounded_breaks[i+1], ']')
}
test_33_simple <- test_33_simple %>%
mutate(faktor_class = factor(cut(faktor, breaks$brks, include.lowest = T), labels = lab_vec))
# map
ggplot(test_33_simple) +
geom_sf(aes(fill = faktor_class), size= 0.2) +
scale_fill_viridis_d() +
theme_minimal()