在 tmap 使用自訂色盤
和 ggplot2 不同,在 ggplot2 中自訂顏色尺度是透過 scale_ 呼叫;在 tmap 中,顏色是在對應的圖層中指定的。舉例來說,對 prop_by_age 中的變數 age_18_24 作圖:
tm_shape(prop_by_age) +
tm_raster(col = "age_18_24")
因為顏色是在 tm_raster() 中對應的,所以色盤的指定也在同一個呼叫裡完成。你只要在 palette 引數中提供一個顏色向量即可。這也是為什麼值得學習如何產生顏色向量的另一個原因。雖然不同套件在從色彩套件指定色盤時可能有各自的速記方式,但通常都會支援傳入一個顏色向量。
現在把上一題用過的一些色盤套用到這個圖上吧。
本練習屬於課程
在 R 視覺化地理空間資料
練習說明
- 在第一個圖中,使用
blups色盤,取代預設值。 - 在第二個圖中,使用
vir色盤,取代預設值。 - 在第三個圖中,使用
rev(mag)色盤,取代預設值。rev()只是將向量的順序反轉,所以會用到相同的顏色,但順序相反。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Generate palettes from last time
library(RColorBrewer)
blups <- brewer.pal(9, "BuPu")
library(viridisLite)
vir <- viridis(9)
mag <- magma(9)
# Use the blups palette
tm_shape(prop_by_age) +
tm_raster("age_18_24") +
tm_legend(position = c("right", "bottom"))
# Use the vir palette
tm_shape(prop_by_age) +
tm_raster("age_18_24") +
tm_legend(position = c("right", "bottom"))
# Use the mag palette but reverse the order
tm_shape(prop_by_age) +
tm_raster("age_18_24") +
tm_legend(position = c("right", "bottom"))