1 2D 히스토그램: hexbin

hexbin 팩키지는 Hexagon Binning을 통해 2차원 평면에 히스토그램을 육각형 도형으로 표현하는 시각화 도구로 매우 큰 데이터를 시각화하는데 유용하다. 기본 알고리즘은 다음과 같다.

  1. the xy plane over the set (range(x), range(y)) is tessellated by a regular grid of hexagons.
  2. the number of points falling in each hexagon are counted and stored in a data structure
  3. the hexagons with count > 0 are plotted using a color ramp or varying the radius of the hexagon in proportion to the counts.

Base R

library(tidyverse)
library(hexbin)

# Create data
hex_df <- tibble(x = rnorm(mean=1.5, 5000),
                 y = rnorm(mean=1.6, 5000))

# Make the plot
bin <- hexbin(hex_df$x, hex_df$y, xbins=40)
plot(bin, main="") 

ggplot2

# Make the ggplot
hex_df %>% 
  ggplot(aes(x=x, y=y)) +
    geom_hex() +
    scale_fill_viridis_c(name="Frequency")

2 R 스티커

Hexagon sticker in R 제작도구가 있어 Tidyverse Korea 미트업에 사용할 로고를 제작해본다.

# install.packages("hexSticker")
library(hexSticker)
library(showtext)
font_add_google("Nanum Gothic", "NanumGothic")

p <- ggplot(aes(x = mpg, y = wt), data = mtcars) + geom_point()
p <- p + theme_void() + theme_transparent()

sticker("fig/Taegeuk.png", package="서울 KRUG", p_family="NanumGothic", p_size=6.5, p_color="#3d3838",
        s_x=1, s_y=.65, s_width=0.45, s_height=0.45,
         h_fill="#d9d9d9", h_color="#636363", spotlight = TRUE, 
        filename="fig/KRUG_Seoul.png")

KRUG 서울 R 스티커

3 지도 → 육각형 1 2

geogrid: Turning geospatial polygons into regular or hexagonal grids 팩키지에 내장된 영국 런던 데이터를 대상으로 원본 지도와 육각형으로 변환시킨 지도를 도식화해서 가능성을 타진한다.

library(geogrid)
library(sf)
library(tmap)

input_file <- system.file("extdata", "london_LA.json", package = "geogrid")
original_shapes <- st_read(input_file) %>% st_set_crs(27700)
Reading layer `london_LA' from data source `/Library/Frameworks/R.framework/Versions/3.5/Resources/library/geogrid/extdata/london_LA.json' using driver `GeoJSON'
Simple feature collection with 33 features and 7 fields
geometry type:  MULTIPOLYGON
dimension:      XY
bbox:           xmin: 503568.2 ymin: 155850.8 xmax: 561957.5 ymax: 200933.9
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
original_shapes$SNAME <- substr(original_shapes$NAME, 1, 4)

원본 데이터

raw_plot <- tm_shape(original_shapes) + 
  tm_polygons("HECTARES", palette = "viridis") +
  tm_text("SNAME")
raw_plot

육각형 변환 지도

## 변환
london_hex <- calculate_grid(shape = original_shapes, grid_type = "hexagonal", seed = 3)
london_hex_map <- assign_polygons(original_shapes, london_hex)

hex_plot <- tm_shape(london_hex_map) + 
  tm_polygons("HECTARES", palette = "viridis") +
  tm_text("SNAME")

hex_plot