使用ggplot2绘制哑铃图
这里要使用到ggalt, 它是ggplot2的扩展包。
# LIBRARIES ----
library(tidyverse)
library(tidyquant)
library(ggalt)
# DATA ----
mpg
# 1.0 DATA WRANGLING ----
# - Learn dplyr in R for Business Analysis DS4B 101-R Course
mpg_by_year_tbl <- mpg %>%
select(hwy, year, model, class) %>%
pivot_wider(
names_from = year,
values_from = hwy,
id_cols = c(class, model),
values_fn = function(x) mean(x, na.rm = TRUE),
names_prefix = "year_"
) %>%
mutate(model = fct_reorder(model, year_2008)) %>%
drop_na()
# 2.0 VISUALIZATION (Dumbell Plots) ----
# - Learn ggplot2 in R for Business Analysis DS4B 101-R Course
# * Basic Dumbbell Plot with ggalt ----
g1 <- mpg_by_year_tbl %>%
ggplot(aes(x = year_1999, xend = year_2008, y = model, group = model)) +
geom_dumbbell(
colour="#a3c4dc",
colour_xend="#0e668b",
size=4.0,
dot_guide=TRUE,
dot_guide_size=0.15,
dot_guide_colour = "grey60"
)
g1
# * Customize Theme with tidyquant ----
g2 <- g1 +
labs(
title = "Change Vehicle Fuel Economy between 1999 and 2008",
x="Fuel Economy (MPG)", y = "Vehicle Model"
) +
theme_tq() +
theme(
panel.grid.minor=element_blank(),
panel.grid.major.y=element_blank(),
panel.grid.major.x=element_line(),
axis.ticks=element_blank(),
panel.border=element_blank()
)
g2
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
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
编辑 (opens new window)
上次更新: 2021/08/18, 21:15:19