/
332-hexbin-chloropleth-cartogram.Rmd
214 lines (128 loc) · 5.76 KB
/
332-hexbin-chloropleth-cartogram.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
---
title: "Basic Cartogram with R"
descriptionMeta: "This post describes how to apply the cartogram method to a hexbin map. Each region is represented as a hexagon which size is distorted according to a numeric variable. Reproducible R code provided."
descriptionTop: "This post explains how to use the `[cartogram](cartogram.html)` method on a `[hexbin map](hexbin-map.html)`. Each region is depicted as a hexagon, with its **size altered based on a numeric variable**, utilizing the `cartogram` package."
sectionText: "Cartogram section"
sectionLink: "cartogram.html"
DataToVizText: "Data to Viz"
DataToVizLink: "data-to-viz.com/graph/cartogram.html"
url: "332-hexbin-chloropleth-cartogram"
output:
html_document:
self_contained: false
mathjax: default
lib_dir: libs
template: template_rgg.html
css: style.css
toc: TRUE
toc_float: TRUE
toc_depth: 2
df_print: "paged"
---
```{r global options, include = FALSE}
knitr::opts_chunk$set(warning = FALSE, message = FALSE, dev = "ragg_png", dpi = 300)
```
<div class="container">
# Basic hexbin map
***
<div class = "row">
<div class = "col-md-6 col-sm-12 align-self-center">
The first step is to build a basic [hexbin map](hexbin-map.html) of the US. Note that the gallery dedicates a [whole section](hexbin-map.html) to this kind of map.
Hexagons boundaries are provided [here](https://team.carto.com/u/andrew/tables/andrew.us_states_hexgrid/public/map). You have to download it at the `geojson` format and load it in R thanks to the `st_read() / read_sf()` functions.
Then you get a geospatial object that you can plot using the `plot()` function. This is widely explained in the [background map](map.html) section of the gallery.
</div>
<div class = "col-md-6 col-sm-12">
```{r thecode, echo=FALSE, out.width = "100%", fig.height=7}
# library
library(tidyverse)
library(sf)
library(RColorBrewer)
# Hexagons boundaries at geojson format were found here, and stored on my github https://team.carto.com/u/andrew/tables/andrew.us_states_hexgrid/public/map.
# Load this file. (Note: I stored in a folder called DATA)
my_sf <- read_sf("DATA/us_states_hexgrid.geojson.json")
# Bit of reformatting
my_sf <- my_sf %>%
mutate(google_name = gsub(" \\(United States\\)", "", google_name))
# Show it
plot(st_geometry(my_sf))
```
</div>
</div>
```{r thecode, eval=FALSE}
```
# Distort hexagone size with `cartogram` {#carto}
***
<div class = "row">
<div class = "col-md-6 col-sm-12 align-self-center">
The geospatial object has an attached data frame that provides several information for each region.
We need to add a new column to this data frame. This column will provide the **population per state**, available at `.csv` format [here](https://raw.githubusercontent.com/holtzy/R-graph-gallery/master/DATA/pop_US.csv).
We can thus use the `cartogram` library to **distort the size of each state** (=hexagon), proportionally to this column. The new geospatial object we get can be drawn with the same `plot` function.
</div>
<div class = "col-md-6 col-sm-12">
```{r thecode2, echo=FALSE, out.width = "100%", fig.height=7}
# Library
library(cartogram)
# Load the population per states (source: https://www.census.gov/data/tables/2017/demo/popest/nation-total.html)
pop <- read.table("https://raw.githubusercontent.com/holtzy/R-graph-gallery/master/DATA/pop_US.csv", sep = ",", header = T)
pop$pop <- pop$pop / 1000000
# merge both
my_sf <- my_sf %>% left_join(., pop, by = c("google_name" = "state"))
# Compute the cartogram, using this population information
# First we need to change the projection, we use Mercator (AKA Google Maps, EPSG 3857)
my_sf_merc <- st_transform(my_sf, 3857)
cartogram <- cartogram_cont(my_sf_merc, "pop")
# Back to original projection
cartogram <- st_transform(cartogram, st_crs(my_sf))
# First look!
plot(st_geometry(cartogram))
```
</div>
</div>
```{r thecode2, eval=FALSE}
```
# Cartogram and choropleth {#choro}
***
To get a satisfying result, let's:
- **color hexagons** according to their population
- add **legend**
- add **background** color
- add **title**
- add state name. Label position is computed thanks to the `gCentroid()` function. The centroid can be understand as the **center of a polygon**, and by so a good **proxy to place the label**.
```{r thecode3, echo=FALSE, fig.align="center", out.width = "80%", fig.height=5}
# Library
# plot
ggplot(cartogram) +
geom_sf(aes(fill = pop), linewidth = 0.05, alpha = 0.9, color = "black") +
scale_fill_gradientn(
colours = brewer.pal(7, "BuPu"), name = "population (in M)",
labels = scales::label_comma(),
guide = guide_legend(
keyheight = unit(3, units = "mm"),
keywidth = unit(12, units = "mm"),
title.position = "top",
label.position = "bottom"
)
) +
geom_sf_text(aes(label = iso3166_2), color = "white", size = 3, alpha = 0.6) +
theme_void() +
ggtitle("Another look on the US population") +
theme(
legend.position = c(0.5, 0.9),
legend.direction = "horizontal",
text = element_text(color = "#22211d"),
plot.background = element_rect(fill = "#f5f5f9", color = NA),
panel.background = element_rect(fill = "#f5f5f9", color = NA),
legend.background = element_rect(fill = "#f5f5f9", color = NA),
plot.title = element_text(size = 22, hjust = 0.5, color = "#4e4d47", margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")),
)
```
```{r thecode3, eval=FALSE}
```
# Going further
This post explains how to use the `cartogram` method on a hexbin map.
You might be interested in interested in [2d density hexbin map](329-hexbin-map-for-distribution.html), and more generally in the [hexbin map section](hexbin-map.html) of the gallery.
<!-- Close container -->
</div>
```{r, echo=FALSE}
htmltools::includeHTML("htmlChunkRelatedMap.html")
```