-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathV42_ggplotly.Rmd
More file actions
203 lines (168 loc) · 7.81 KB
/
V42_ggplotly.Rmd
File metadata and controls
203 lines (168 loc) · 7.81 KB
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
```{r include=FALSE}
knitr::opts_chunk$set(cache = T, warning = F, message = F,
class.output = "output", out.width='100%',
fig.asp = 0.5, fig.align = 'center')
```
## ggplotly
[Scatter plots with ggplot2 (plotly.com)](https://plotly.com/ggplot2/line-and-scatter/)
```{r include=FALSE}
library(tidyverse)
options(scipen = 999)
th <- theme_minimal() +
theme(
title = element_text(family="Noto Sans CJK TC"), #all title elements
text = element_text(family="Noto Sans CJK TC"), #all text elements
plot.title = element_text(face="bold"),
axis.title.x = element_text(hjust=1, face="bold.italic"),
axis.title.y = element_text(hjust=1, face="bold.italic"),
)
```
### LINE CHART
[Line plots with R (plotly.com)](https://plotly.com/r/line-charts/)
```{r plotly-clean-NW, message=FALSE, warning=FALSE}
NW <- read_csv("data/interactive_bulletin_charts_agecl_median.csv") %>%
select(Category, year, Net_Worth) %>%
group_by(Category) %>%
arrange(year) %>%
ungroup()
```
如果希望滑鼠在移到折線上時就會有浮出的資訊(tips)顯示該資料點的屬性特徵,可以採用`plotly()`這個套件。這個套件原本就是做線上互動圖表的,但他開發了R client讓R的使用者可以很輕易地把ggplot2的結果轉為互動圖表。但這所謂的互動也僅限於滑鼠移過去所浮出的資訊罷了,不過已經能夠達到吸引部分讀者目光、提供訊息的效果。
而plotly的設計非常簡單,就是把ggplot的結果指給一個變數後,然後用`ggplotly(NW.plot)`將其轉為plotly即可。但要注意的是,並不是每一個圖都可以順利轉換。例如本節最後一個例子Treemap便無法成功轉換。
設定:原本plotly會帶一個操控列,可以在`ggplotly()`指令後加入`config()`便可將其隱藏。
```{r plotly-NW-plot1, message=FALSE, warning=FALSE}
NW.plot <- NW %>%
ggplot() +
aes(year, Net_Worth, color=Category) +
geom_line() +
theme_minimal() +
labs(title = "Net Worth by year grouped by age groups",
x = "Year",
y = "Net Worth") + th
library(plotly)
ggplotly(NW.plot) %>%
config(displayModeBar = FALSE)
```
可以在`aes()`設定要帶入圖的變數時,新增一個`text`變數,手動設定要呈現的動態呈現方塊。但要注意的是,要多加入一個`group=1`才能夠作用(WHY?)。但前例浮出視窗的原始內容所顯示的是原本的變數名稱和值,往往不易觀察。比較好的方式是在下`ggplot() + aes()`指令時,在`aes()`中指定`text`來作為後續浮出視窗內容。指定方法如下。要注意的是,該浮出視窗的語法是HTML,所以如果要改寫浮出視窗內容,要用`paste0()`將變數和HTML的標籤給銜接起來。以下例子中的`<b>`代表粗體的意思,`<br>`則是換行符號。
```{r plotly-NW-plot2, message=FALSE, warning=FALSE}
NW.plot <- NW %>%
ggplot() +
aes(year, Net_Worth,
color=Category,
text = paste0("<b>年(X): </b>", year, "<br>",
"<b>淨資產(Y): </b>", Net_Worth,"<br>",
"<b>年齡組: </b>", Category),
group=1) +
geom_line() +
theme_minimal() +
labs(title = "Net Worth by year grouped by age groups",
x = "Year",
y = "Net Worth") + th
ggplotly(NW.plot, tooltip = "text") %>%
config(displayModeBar = FALSE)
```
其他例子中使用`ggplotly()`都是直接照前面的方法套用即可。唯獨在Treemap中無法用這樣的方法來做互動的視覺化。想想這也正常,畢竟Treemap是用非ggplot的第三方套件(`library(treemapify)`)。
除此之外,可以把R Markdown中Code Cell的的設定加入`include=FALSE`,這樣可以讓RMD在編製為HTML檔時,不要顯示程式碼,而直接顯示互動的視覺化介面。
### SCATTER
```{r plotly-clean-unicef, message=FALSE, warning=FALSE}
bw <- read_csv("data/unicef-changing-childhood-data.csv") %>%
select(country = WP5, age = WP22140, bw = WP22092) %>%
mutate(country = ordered(country,
levels=c(1, 3, 4, 10, 11, 12, 13, 14, 17,
29, 31, 33, 35, 36, 60, 61, 77,
79, 81, 87, 165),
labels=c("USA", "Morocco", "Lebanon",
"Indonesia","Bangladesh", "UK",
"France", "Germany", "Spain",
"Japan", "India", "Brazil",
"Nigeria", "Kenya", "Ethiopia",
"Mali", "Ukraine", "Cameroon",
"Zimbabwe","Argentina", "Peru"))) %>%
count(country, age, bw) %>%
group_by(country, age) %>%
mutate(perc = n/sum(n)) %>%
ungroup() %>%
filter(bw == 1) %>%
select(country, age, perc) %>%
spread(age, perc) %>%
rename(`15-24y` = `1`, `40+y` = `2`)
```
```{r plotly-ggplot-unicef, message=FALSE, warning=FALSE}
bw.p <- bw %>%
ggplot() + aes(`40+y`, `15-24y`, label = country) +
geom_point(color = "skyblue", size = 2) +
xlim(0.2, 0.85) + ylim(0.2, 0.85) +
geom_text(hjust = -0.1, vjust = -0.5) +
geom_abline(intercept = 0, slop = 1,
color="lightgrey", alpha=0.5, linetype="dashed") +
th +
theme(aspect.ratio=1)
```
```{r plotly-ggplotly, message=FALSE, warning=FALSE}
bw.p %>% ggplotly()
```
### Barplot
[Bar charts with R (plotly.com)](https://plotly.com/r/bar-charts/)
```{r plotly-clean-twpopulation, message=FALSE, warning=FALSE}
county <- read_csv("data/tw_population_opendata110N010.csv") %>%
slice(-1, -(370:375)) %>%
type_convert() %>%
mutate(county = str_sub(site_id, 1, 3)) %>%
group_by(county) %>%
summarize(
area = sum(area),
people_total = sum(people_total)
) %>%
ungroup()
population.p <- county %>%
mutate(county = reorder(county, people_total)) %>%
ggplot() + aes(county, people_total) %>%
geom_col(fill="skyblue") +
coord_flip() + th
```
```{r plotly-twpopulation}
population.p %>% ggplotly()
```
### Boxplot
[Box plots with ggplot2 (plotly.com)](https://plotly.com/ggplot2/box-plots/)
```{r plotly-clean-AQI, message=FALSE, warning=FALSE}
aqi.toplot <- read_rds("https://github.com/p4css/R4CSS/raw/master/data/AQI_Chaozhou.rds") %>%
arrange(日期)%>%
filter(測項=="PM2.5") %>%
gather("hour", "PM25", 4:28) %>%
mutate(PM25 = as.numeric(PM25)) %>%
drop_na() %>%
mutate(year = lubridate::year(日期), month = lubridate::month(日期)) %>%
filter(month %in% c(11, 12, 1, 2, 3))
aqi.plot <- aqi.toplot %>%
mutate(year = as.character(year)) %>%
ggplot() + aes(x=year, y=PM25) +
geom_boxplot(fill="skyblue", alpha=0.2) +
ylim(0, 200) +
coord_flip() +
theme_minimal()
```
```{r plotly-AQI, message=FALSE, warning=FALSE}
aqi.plot %>% ggplotly
```
### Treemap (Global Carbon)
其他例子中使用`ggplotly()`都是直接照前面的方法套用即可。唯獨在Treemap中無法用這樣的方法來做互動的視覺化。想想這也正常,畢竟Treemap是用非ggplot的第三方套件(`library(treemapify)`)。
```{r plotly-clean-treemap, message=FALSE, warning=FALSE}
totreemap <- read_csv("data/GCB2021v34_MtCO2_flat.csv") %>%
drop_na(`Total`) %>%
filter(!Country %in% c("Global", "International Transport")) %>%
filter(Year==2020) %>%
arrange(desc(`Total`)) %>%
mutate(perc = Total/sum(Total)) %>%
slice(1:20)
library(treemapify)
carbon.p <- totreemap %>%
ggplot() + aes(area = perc, fill=`Per Capita`, label=Country) +
geom_treemap() +
geom_treemap_text(color="white",
place="centre",
grow=TRUE
)
```
```{r fail-ggplotly}
# carbon.p %>% ggplotly
```