使用 ggplot 繪製 sf
你可能已經很熟悉 ggplot2 函式庫,ggplot 的圖是由多個圖層組成的。
事實上,sf 物件也能用 ggplot2 來繪製。快速複習一下:第一個圖層是由 ggplot() 建立的空白畫布。後續的圖層則透過加入各種 geom 函式(形式為 geom_<plot>)、labs()、主題等,彼此堆疊上去。
接下來,你會用多個 sf 物件來建立一張 ggplot 地圖。
listings 資料框、多重多邊形 london_poly,以及一組點 num_listings 都已經載入。tidyverse 與 sf 函式庫也都已匯入。
本練習屬於課程
使用 shinydashboard 建立儀表板
練習說明
- 將
num_listings的座標參考系統(CRS)設成與london_poly相同。 - 把多重多邊形加入空白畫布。
- 設定
fill參數,讓每個鄰里(見Name屬性)都有不同的填色。 - 在每個多邊形的中心加入標籤。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Set the CRS of num_listings to that of london_poly
st_crs(num_listings) <- ___(___)
# Add the multipolygon to the blank canvas
___ +
# Set a different fill for each neighborhood
geom_sf(aes(___)) +
# Add a label at the center of each polygon
___(data=num_listings, aes(label=`Number of listings`)) +
theme_classic()