I’ve been gradually learning how to draw maps using R programming. The key to a map graph is mapping colors to regions, so I’ve been studying related ggplot
functions one by one. In this post, I plan to write about how to map colors using the viridis
scale.
I executed the read_sf
function to read the prepared SHP file.
map1 = read_sf('./sig.shp')
I converted the Korean data within the SHP file from EUC-KR to UTF-8 encoding, and due to the large map size, you reduced it by 1/1000 using the ms_simplify
function.
map3 = map1 |>
mutate(SIG_KOR_NM = iconv(SIG_KOR_NM, from = "EUC-KR", to = 'UTF-8')) |>
st_set_crs(5179) |>
ms_simplify(keep = 0.001, keep_shapes = T)
If the data is ready, you can draw the map with just two lines of code.
ggplot(map3) +
geom_sf()
If you specify a column for the fill
parameter, colors are automatically mapped. If you want to use a different theme instead of the default colors, try using scale_fill_viridis_d
.
ggplot(map3) +
geom_sf(aes(fill = SIG_CD)) +
theme(legend.position = "none")
scale_fill_viridis_d
The scale_fill_viridis_d
function provides visually uniform color maps for both color and grayscale, designed to be perceptually uniform even for viewers with common forms of colorblindness. scale_fill_viridis_d
is used to adjust colors for discrete (categorical) data. There’s also scale_fill_viridis_c
, which is used when mapping colors for continuous data, but the basic usage is the same.
The option
parameter within the function is a string representing the color theme. You can use 8 options, indicated by the letters A to H.
ggplot(map3) +
geom_sf(aes(fill = SIG_CD)) +
scale_fill_viridis_d(option = "A") + # A ~ H 입력.
theme(legend.position = "none")
The color range is based on a scale from 0 to 1. If you don’t like the extreme colors, you can use the begin
and end
parameters to narrow the range.
ggplot(map3) +
geom_sf(aes(fill = SIG_CD)) +
scale_fill_viridis_d(begin = 0.5, end = 1) +
theme(legend.position = "none")