区间刻度示例
让我们回到先前绘制的人口中 18–24 岁比例的地图:
tm_shape(prop_by_age) +
tm_raster("age_18_24", palette = vir) +
tm_legend(position = c("right", "bottom"))
这幅图的问题在于:大多数比例都落在最低的颜色级别里,因此图中细节不明显。解决这个问题的一种方法是:不要把变量范围按等宽分箱,而是把它划分为更有用的类别。
先来复现 tmap 的默认分箱:5 个类别,使用 "pretty" 断点切分。然后,您可以尝试用其他方法把变量切分为若干区间。直接使用 classIntervals() 函数能让您快速看到断点位置,但检验一组断点是否合适,最好的方式还是把它们画出来。
(顺带一提,解决此类问题的另一种方法是对变量做变换,使得在变换后的刻度上使用等宽分箱更有意义。)
本练习是课程的一部分
在 R 中可视化地理空间数据
练习说明
- 对
values(prop_by_age[["age_18_24"]])调用classIntervals(),设置n = 5且style = "pretty"。提示:问题看到了吗?有 130,770 个网格单元落入了第一个分箱。 - 现在保持上述调用不变,但将
style改为"quantile"。 - 在作图的
tm_raster()图层中传入n和style参数,使用等样本量的分箱。 - 为
values(prop_by_age[["age_18_24"]])绘制直方图。您会把断点放在哪里? - 在
tm_raster()中自定义断点:breaks = c(0.025, 0.05, 0.1, 0.2, 0.25, 0.3, 1)。 - 使用
tmap_save()将最终图保存为 leaflet 图,filename设为"prop_18-24.html"。
交互式实操练习
通过完成这段示例代码来试试这个练习。
mag <- viridisLite::magma(7)
library(classInt)
# Create 5 "pretty" breaks with classIntervals()
# Create 5 "quantile" breaks with classIntervals()
# Use 5 "quantile" breaks in tm_raster()
tm_shape(prop_by_age) +
tm_raster("age_18_24", palette = mag) +
tm_legend(position = c("right", "bottom"))
# Create histogram of proportions
# Use fixed breaks in tm_raster()
tm_shape(prop_by_age) +
tm_raster("age_18_24", palette = mag,
style = "fixed")
# Save your plot to "prop_18-24.html"