进出口数据溪流图

进出口数据溪流图

本文是学习Streamgraphs: Economic trade flows with R的笔记。讲述了如何使用O.E.C. API获取的数据绘制朝鲜进出口数据的溪流图。

整理数据:

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
# devtools::install_github('hrbrmstr/streamgraph')
library(streamgraph)
library(jsonlite)
library(tidyverse)
library(hrbrthemes)
trade <- read_json('http://atlas.media.mit.edu/hs92/import/1995.2017/prk/show/all/', simplifyVector = T) %>%
data.frame()

countries <- read_json('http://atlas.media.mit.edu/attr/country/', simplifyVector = T) %>%
data.frame() %>%
mutate(groups = case_when(
grepl("China", data.name) ~ "China",
grepl("India", data.name) ~ "India",
grepl("Japan", data.name) ~ "Japan",
is.na(data.name) ~ "Unknown",
T ~ "Other Countries"
))

trade$groups <- countries$groups[match(trade$data.dest_id, countries$data.id)]
trade$data.import_val[is.na(trade$data.import_val)] <- 0
trade$data.export_val[is.na(trade$data.export_val)] <- 0
trade$data.export_val <- trade$data.export_val*-1

export.data <- aggregate(
trade$data.export_val,
by = list(trade$data.year,
trade$groups),
sum)

import.data <- aggregate(
trade$data.import_val,
by = list(trade$data.year,
trade$groups),
sum)
trade.data <- cbind(export.data, import = import.data$x)
names(trade.data)[1:3] <- c('year', 'country', 'export')

使用ggplot2绘制溪流图:

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
ggplot(trade.data) + 
geom_area(aes(x = year,
y = import,
fill = country),
alpha = 0.95) +
geom_area(aes(x = year,
y = export,
fill = country),
alpha = 0.95) +
annotate('text', x = 1995, y = 3000000000,
label = '进口', color = '#cccccc',
family = 'STSong') +
annotate('text', x = 1995, y = -3000000000,
label = '出口', color = '#cccccc',
family = 'STSong') +
geom_hline(yintercept = 0, color = 'white') +
scale_fill_brewer('国家', palette = 'Set2') +
theme_ipsum(grid = 'Y',
base_family = 'STSongti-SC-Bold') +
expand_limits(y = c(4000000000, -4000000000)) +
scale_y_comma(labels = abs_comma) +
theme(legend.position = 'bottom') +
guides(fill = guide_legend(ncol = 2)) +
labs(title = '朝鲜的进出口情况',
subtitle = '单位:美元',
y = '美元',
caption = '数据来源:O.E.C. API\nhttp://atlas.media.mit.edu/api/')

使用streamgraph包绘制溪流图:

1
2
3
4
5
6
import.data %>% 
streamgraph("Group.2", "x",
"Group.1", offset = 'zero') %>%
sg_axis_x('Group.2') %>%
sg_axis_y(tick_format = '$.0s') %>%
sg_fill_brewer('Spectral')

1
2
3
4
5
6
export.data %>% 
streamgraph("Group.2", "x",
"Group.1", offset = 'zero') %>%
sg_axis_x('Group.2') %>%
sg_axis_y(tick_format = '$.0s') %>%
sg_fill_brewer('Spectral')

可以看出,中国是朝鲜最大的贸易伙伴。

# R

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×