Self introduction

Personal Website My research journey

needed packages

ggplot2: data visualization
sf: for reading and processing spatial data
tmap: map
tmaptools: for reading and processing spatial data
leaflet: for interactive maps
dplyr: for data mutation
*tidyverse: for a lot of necessarily packages for everyday data analyses

sf, tmap are different mapping packages for the same purpose.
Personally, I like tmap more.

basic concepts

leaflet()%>%addTiles()

import coordinates

setwd("C:/Users/wenra/Downloads")
moto<-readr::read_csv("C:/Users/wenra/Downloads/中油_電動機車充電站.csv")
## 
## -- Column specification --------------------------------------------------------
## cols(
##   站代號 = col_character(),
##   站名 = col_character(),
##   郵遞區號 = col_double(),
##   地址 = col_character(),
##   經度 = col_double(),
##   緯度 = col_double(),
##   電話 = col_character(),
##   提供服務時段 = col_character()
## )
leaflet()%>%addTiles()%>%
  addCircleMarkers(data=moto,lat=~緯度, lng=~經度,radius=~3)

pop-up information

names(moto)
## [1] "站代號"       "站名"         "郵遞區號"     "地址"         "經度"        
## [6] "緯度"         "電話"         "提供服務時段"
moto<-moto%>%mutate(popup_info=paste("站名: ",站名,"<br/>",
                           "電話: ", 電話,"<br/>",
                           "提供服務時段: ", 提供服務時段))

motomap<-leaflet()%>%addTiles()%>%addCircleMarkers(data=moto,lat=~緯度, lng=~經度,radius=~3,popup = ~popup_info)

save a map

mapshot(motomap, url = "moto.html")

import data

step 1. Search for shp file.

Taiwan county map

Or you can check if any R packages contains map information.

  1. world: rnaturalearth

  2. USA: usmap

step 2. what do you want to see?

I want to see if DPP won more votes in Southern counties than the KMT.

Central Election Commission

主計處 縣市重要統計指標

step 3. check they have a common variable to merge

  1. 縣市名稱的寫法是否相同 ex: 台北or 台北市

  2. 變數名稱是否相同 ex: countyname or 縣市名稱–>str()

step 4. merge datasets

setwd("C:/Users/wenra/Box Sync/map_taiwan")
taiwan <- st_read("C:/Users/wenra/Box Sync/map_taiwan/COUNTY_MOI_1090820.shp", quiet = TRUE)
str(taiwan) 
taiwan<-st_as_sf(taiwan)
countyvote<-readr::read_csv("C:/Users/wenra/Box Sync/map_taiwan/2018_county_mayor_election.csv")
## 
## -- Column specification --------------------------------------------------------
## cols(
##   COUNTYNAME = col_character(),
##   name = col_character(),
##   number = col_character(),
##   gender = col_character(),
##   birthyear = col_character(),
##   party = col_character(),
##   vote_share = col_double(),
##   vote_ratio = col_double(),
##   elected = col_double(),
##   是否現任 = col_double()
## )
#clean the data

dt_partyvote<-countyvote %>%
  group_by(COUNTYNAME, party) %>%
  summarize(party_vote = vote_ratio)
## `summarise()` has grouped output by 'COUNTYNAME', 'party'. You can override using the `.groups` argument.
DPP<-subset(dt_partyvote,party%in%c("民主進步黨"))
KMT<-subset(dt_partyvote,party%in%c("中國國民黨"))

#shp file is always left. 
map_DPP<-inner_join(taiwan, DPP)
## Joining, by = "COUNTYNAME"
map_KMT<-inner_join(taiwan, KMT)
## Joining, by = "COUNTYNAME"
names(map_DPP)[names(map_DPP) == "party_vote"] <-"DPP_vote_ratio" 
names(map_KMT)[names(map_KMT) == "party_vote"] <-"KMT_vote_ratio" 
party2018<-cbind(map_DPP,map_KMT)
class(map_DPP)
str(map_DPP)

draw maps using tmap

*polygons: a closed plane figure bounded by straight lines

This means the 行政區 in this file.

tm_shape(map_DPP) +
  tm_polygons(col = "COUNTYNAME")+
  tm_layout(legend.outside = TRUE) 

tm_shape(map_DPP) +
  tm_polygons(col = "DPP_vote_ratio",
              legend.hist = TRUE) +
  tm_layout(legend.outside = TRUE) 

tm_shape(map_KMT) +
  tm_polygons(col = "COUNTYNAME")+
  tm_layout(legend.outside = TRUE) 

tm_shape(map_KMT) +
  tm_polygons(col = "KMT_vote_ratio",
              legend.hist = TRUE) +
  tm_layout(legend.outside = TRUE) 

tm_shape(party2018) +
  tm_polygons(col = "KMT_vote_ratio",
              legend.hist = TRUE) +
  tm_layout(legend.outside = TRUE) 

draw the map using ggplots

We can also use ggplot to draw a map.
1)ggplot: dataset
2)aes: the size of our picture When we paint, we need to decide which kind of paper, color, size of the paper, the layout, and aes helps us define these parameters.

note:

a)aes(geometry = geometry –>so we can make sure that R treats “map_DPP” as spatial data form

b)coord_sf(): not necessary, but if we want Taiwan to be in the center of the map

ggplot(map_DPP)+
  geom_sf(aes(geometry = geometry, fill=DPP_vote_ratio))+
  coord_sf(xlim = c(115, 125), ylim = c(20, 30), expand = FALSE)

ggplot(map_KMT)+
  geom_sf(aes(geometry = geometry, fill=KMT_vote_ratio))+
  coord_sf(xlim = c(115, 125), ylim = c(20, 30), expand = FALSE)

styles

jenks: identifies groups of similar values in the data and maximizes the differences between categories.

For more kinds of styles:
https://geocompr.github.io/post/2019/tmap-color-scales/#fn2

style = “pretty”, the default setting, rounds breaks into whole numbers where possible and spaces them evenly;

style = “equal” divides input values into bins of equal range and is appropriate for variables with a uniform distribution (not recommended for variables with a skewed distribution as the resulting map may end-up having little color diversity);

style = “quantile” ensures the same number of observations fall into each category (with the potential downside that bin ranges can vary widely);

style = “jenks” identifies groups of similar values in the data and maximizes the differences between categories;

style = “cont” (and “order”) present a large number of colors over continuous color fields and are particularly suited for continuous rasters (“order” can help visualize skewed distributions);

style = “cat” was designed to represent categorical values and assures that each category receives a unique color.

party2018
## Simple feature collection with 22 features and 12 fields
## Active geometry column: geometry
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 114.3593 ymin: 10.37135 xmax: 124.5611 ymax: 26.38528
## Geodetic CRS:  TWD97
## First 10 features:
##    COUNTYID COUNTYCODE COUNTYNAME         COUNTYENG      party DPP_vote_ratio
## 1         Z      09007     連江縣 Lienchiang County 民主進步黨           0.00
## 2         G      10002     宜蘭縣      Yilan County 民主進步黨           0.38
## 3         N      10007     彰化縣   Changhua County 民主進步黨           0.40
## 4         M      10008     南投縣     Nantou County 民主進步黨           0.33
## 5         P      10009     雲林縣     Yunlin County 民主進步黨           0.42
## 6         C      10017     基隆市      Keelung City 民主進步黨           0.54
## 7         A      63000     臺北市       Taipei City 民主進步黨           0.17
## 8         F      65000     新北市   New Taipei City 民主進步黨           0.43
## 9         B      66000     臺中市     Taichung City 民主進步黨           0.42
## 10        D      67000     臺南市       Tainan City 民主進步黨           0.38
##    COUNTYID.1 COUNTYCODE.1 COUNTYNAME.1       COUNTYENG.1    party.1
## 1           Z        09007       連江縣 Lienchiang County 中國國民黨
## 2           G        10002       宜蘭縣      Yilan County 中國國民黨
## 3           N        10007       彰化縣   Changhua County 中國國民黨
## 4           M        10008       南投縣     Nantou County 中國國民黨
## 5           P        10009       雲林縣     Yunlin County 中國國民黨
## 6           C        10017       基隆市      Keelung City 中國國民黨
## 7           A        63000       臺北市       Taipei City 中國國民黨
## 8           F        65000       新北市   New Taipei City 中國國民黨
## 9           B        66000       臺中市     Taichung City 中國國民黨
## 10          D        67000       臺南市       Tainan City 中國國民黨
##    KMT_vote_ratio                       geometry                     geometry.1
## 1            0.66 MULTIPOLYGON (((119.9645 25... MULTIPOLYGON (((119.9645 25...
## 2            0.49 MULTIPOLYGON (((121.9597 24... MULTIPOLYGON (((121.9597 24...
## 3            0.53 MULTIPOLYGON (((120.4566 24... MULTIPOLYGON (((120.4566 24...
## 4            0.67 MULTIPOLYGON (((121.2709 24... MULTIPOLYGON (((121.2709 24...
## 5            0.54 MULTIPOLYGON (((120.0811 23... MULTIPOLYGON (((120.0811 23...
## 6            0.46 MULTIPOLYGON (((121.7102 25... MULTIPOLYGON (((121.7102 25...
## 7            0.41 MULTIPOLYGON (((121.571 25.... MULTIPOLYGON (((121.571 25....
## 8            0.57 MULTIPOLYGON (((121.5375 25... MULTIPOLYGON (((121.5375 25...
## 9            0.57 MULTIPOLYGON (((121.3283 24... MULTIPOLYGON (((121.3283 24...
## 10           0.32 MULTIPOLYGON (((120.4402 23... MULTIPOLYGON (((120.4402 23...
countyvote$name
##  [1] "蘇柏豪"                         "朱秀珍"                        
##  [3] "魏耀乾"                         "劉增應"                        
##  [5] "楊鎮浯"                         "洪志恒"                        
##  [7] "汪承樺"                         "陳福海"                        
##  [9] "謝宜璋"                         "洪和成"                        
## [11] "林信華"                         "林姿妙"                        
## [13] "陳歐珀"                         "林錦坤"                        
## [15] "陳秋境"                         "楊文科"                        
## [17] "葉芳棟"                         "鄭朝方"                        
## [19] "徐欣瑩"                         "朱泰平"                        
## [21] "徐定禎"                         "黃玉燕"                        
## [23] "徐耀昌"                         "魏明谷"                        
## [25] "王惠美"                         "白雅燦"                        
## [27] "黃文玲"                         "洪敏雄"                        
## [29] "林明溱"                         "洪國浩"                        
## [31] "林佳瑜"                         "李進勇"                        
## [33] "王麗萍"                         "張麗善"                        
## [35] "翁章梁"                         "吳芳銘"                        
## [37] "林國龍"                         "吳育仁"                        
## [39] "李鎔任"                         "蘇清泉"                        
## [41] "潘孟安"                         "鄺麗貞"                        
## [43] "劉櫂豪"                         "黃裕斌"                        
## [45] "彭權國"                         "饒慶鈴"                        
## [47] "徐榛蔚"                         "劉曉玫"                        
## [49] "<U+9EC4>師鵬"                   "翁珍聖"                        
## [51] "鄭清發"                         "陳大松"                        
## [53] "吳政隆"                         "賴峰偉"                        
## [55] "陳光復"                         "呂華苑"                        
## [57] "謝立功"                         "林右昌"                        
## [59] "謝文進"                         "李驥<U+7FA3>"                  
## [61] "黃源甫"                         "許明財"                        
## [63] "郭榮睿"                         "林智堅"                        
## [65] "蕭淑麗"                         "黃敏惠"                        
## [67] "黃宏成台灣阿成世界偉人財神總統" "涂醒哲"                        
## [69] "吳<U+855A>洋"                   "丁守中"                        
## [71] "姚文智"                         "柯文哲"                        
## [73] "李錫錕"                         "韓國瑜"                        
## [75] "陳其邁"                         "璩美鳳"                        
## [77] "蘇盈貴"                         "蘇貞昌"                        
## [79] "侯友宜"                         "宋原通"                        
## [81] "林佳龍"                         "盧秀燕"                        
## [83] "黃偉哲"                         "高思博"                        
## [85] "林義豐"                         "許忠信"                        
## [87] "陳永和"                         "蘇煥智"                        
## [89] "朱梅雪"                         "陳學聖"                        
## [91] "楊麗環"                         "吳富彤"                        
## [93] "鄭文燦"                         "."                             
## [95] "."                              "."
elected<-subset(countyvote,elected==1)
partyelection<- left_join(party2018, elected, by= "COUNTYNAME")
partyelection      
## Simple feature collection with 22 features and 21 fields
## Active geometry column: geometry
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 114.3593 ymin: 10.37135 xmax: 124.5611 ymax: 26.38528
## Geodetic CRS:  TWD97
## First 10 features:
##    COUNTYID COUNTYCODE COUNTYNAME         COUNTYENG    party.x DPP_vote_ratio
## 1         Z      09007     連江縣 Lienchiang County 民主進步黨           0.00
## 2         G      10002     宜蘭縣      Yilan County 民主進步黨           0.38
## 3         N      10007     彰化縣   Changhua County 民主進步黨           0.40
## 4         M      10008     南投縣     Nantou County 民主進步黨           0.33
## 5         P      10009     雲林縣     Yunlin County 民主進步黨           0.42
## 6         C      10017     基隆市      Keelung City 民主進步黨           0.54
## 7         A      63000     臺北市       Taipei City 民主進步黨           0.17
## 8         F      65000     新北市   New Taipei City 民主進步黨           0.43
## 9         B      66000     臺中市     Taichung City 民主進步黨           0.42
## 10        D      67000     臺南市       Tainan City 民主進步黨           0.38
##    COUNTYID.1 COUNTYCODE.1 COUNTYNAME.1       COUNTYENG.1    party.1
## 1           Z        09007       連江縣 Lienchiang County 中國國民黨
## 2           G        10002       宜蘭縣      Yilan County 中國國民黨
## 3           N        10007       彰化縣   Changhua County 中國國民黨
## 4           M        10008       南投縣     Nantou County 中國國民黨
## 5           P        10009       雲林縣     Yunlin County 中國國民黨
## 6           C        10017       基隆市      Keelung City 中國國民黨
## 7           A        63000       臺北市       Taipei City 中國國民黨
## 8           F        65000       新北市   New Taipei City 中國國民黨
## 9           B        66000       臺中市     Taichung City 中國國民黨
## 10          D        67000       臺南市       Tainan City 中國國民黨
##    KMT_vote_ratio   name number gender birthyear              party.y
## 1            0.66 劉增應      4     男      1958           中國國民黨
## 2            0.49 林姿妙      2     女      1952           中國國民黨
## 3            0.53 王惠美      2     女      1968           中國國民黨
## 4            0.67 林明溱      1     男      1951           中國國民黨
## 5            0.54 張麗善      4     女      1964           中國國民黨
## 6            0.46 林右昌      2     男      1971           民主進步黨
## 7            0.41 柯文哲      4     男      1959 無黨籍及未經政黨推薦
## 8            0.57 侯友宜      2     男      1957           中國國民黨
## 9            0.57 盧秀燕      3     女      1961           中國國民黨
## 10           0.32 黃偉哲      1     男      1963           民主進步黨
##    vote_share vote_ratio elected 是否現任                       geometry
## 1        4861       0.66       1        1 MULTIPOLYGON (((119.9645 25...
## 2      123767       0.49       1        0 MULTIPOLYGON (((121.9597 24...
## 3      377795       0.53       1        0 MULTIPOLYGON (((120.4566 24...
## 4      195385       0.67       1        1 MULTIPOLYGON (((121.2709 24...
## 5      210770       0.54       1        0 MULTIPOLYGON (((120.0811 23...
## 6      102167       0.54       1        1 MULTIPOLYGON (((121.7102 25...
## 7      580663       0.41       1        1 MULTIPOLYGON (((121.571 25....
## 8     1165130       0.57       1        0 MULTIPOLYGON (((121.5375 25...
## 9      827996       0.57       1        0 MULTIPOLYGON (((121.3283 24...
## 10     367518       0.38       1        0 MULTIPOLYGON (((120.4402 23...
##                        geometry.1
## 1  MULTIPOLYGON (((119.9645 25...
## 2  MULTIPOLYGON (((121.9597 24...
## 3  MULTIPOLYGON (((120.4566 24...
## 4  MULTIPOLYGON (((121.2709 24...
## 5  MULTIPOLYGON (((120.0811 23...
## 6  MULTIPOLYGON (((121.7102 25...
## 7  MULTIPOLYGON (((121.571 25....
## 8  MULTIPOLYGON (((121.5375 25...
## 9  MULTIPOLYGON (((121.3283 24...
## 10 MULTIPOLYGON (((120.4402 23...
view(partyelection)

create interactive map

map<-st_as_sf(partyelection)
tm_shape(partyelection)+
  tm_polygons("KMT_vote_ratio",id="COUNTYNAME",palette="Blues",
              popup.vars=c(
                    "2018縣市長國民黨的得票率: "="KMT_vote_ratio",
                    "當選縣市長: " = "name",
                    "當選縣市長的政黨別:"="party.y",
                    "當選者的得票數:"="vote_share")  
                )

tmap_mode("view")
## tmap mode set to interactive viewing
kmt_2018_countyelection<-tmap_last()
tmap_save(kmt_2018_countyelection,"kmt_2018_countyelection.html")
## Interactive map saved to C:\Users\wenra\Downloads\kmt_2018_countyelection.html