library(maptools)
## Loading required package: sp
## Checking rgeos availability: TRUE
library(ggmap)
## Loading required package: ggplot2
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
library(sf)
## Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
library(tmap)
library(RColorBrewer)
library(ggplot2)
library(raster)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:raster':
## 
##     intersect, select, union
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
twpop <- read.table("twPop2011.txt", h = T)
knitr::kable(head(twpop, 2))
id pop
Changhua 1304216
Chiayi 812781
twpop$pcpop <- twpop$pop/sum(unique(twpop$pop))
list(twpop)
## [[1]]
##                id     pop       pcpop
## 1        Changhua 1304216 0.054649088
## 2          Chiayi  812781 0.034057043
## 3   Chiayi County  812781 0.034057043
## 4    Hsinchu City  932379 0.039068423
## 5  Hsinchu County  932379 0.039068423
## 6         Hualien  337557 0.014144269
## 7       Kaohsiung 2772461 0.116171297
## 8         Keelung  381770 0.015996876
## 9          Kinmen  122723 0.005142323
## 10      Lienkiang  561490 0.023527480
## 11         Miaoli  560813 0.023499113
## 12         Nantou  524426 0.021974429
## 13     New Taipei 3903745 0.163574211
## 14         Penghu  206298 0.008644272
## 15       Pingtung  868827 0.036405475
## 16       Taichung 2655456 0.111268569
## 17         Tainan 1874724 0.078554439
## 18         Taipei 2635766 0.110443521
## 19        Taitung  229420 0.009613127
## 20        Taoyuan 2005795 0.084046559
## 21          Yilan  459349 0.019247582
## 22          Yulin  715288 0.029971904
twpop$gvotes <- c(19, 27, 32, 16, -0.6, -25, 28, 
          7, -53, -58, 8, 6, 18, 
          12, 27, 19, 38, 11, -20,20, 31, 27) 

tw2 <- getData('GADM', country='TW', level=2) %>% fortify(region = "NAME_2")
d0 <- summarise(group_by(tw2, id), latc=mean(lat), longc=mean(long))
knitr::kable(head(d0, 2))
id latc longc
Changhua 24.04460 120.388
Chiayi City 23.47536 120.450
ggplot() +
geom_map(data=twpop, 
         aes(map_id=id, 
             fill=gvotes), 
         map=tw2) +
 expand_limits(x=tw2$long, 
               y=tw2$lat) +
 geom_text(data=d0, 
           aes(x=longc, 
               y=latc, 
               label=id), 
           size=2.5, 
           color="gold4") +
scale_fill_distiller(name="gvotes", 
                    breaks=scales::pretty_breaks(n=5)) +   scale_fill_gradient(low = "blue",high = "green")+
theme_nothing(legend=TRUE)
## Scale for 'fill' is already present. Adding another scale for 'fill', which
## will replace the existing scale.

##漸層的民意示意圖