-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy path1_Line_Plots.Rmd
234 lines (198 loc) · 10.6 KB
/
1_Line_Plots.Rmd
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
---
title: "Creating plots in R using ggplot2 - part 1: line plots"
author:
- Jodie Burchell
- Mauricio Vargas Sepúlveda
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, cache = FALSE, echo = FALSE, message = FALSE, warning = FALSE, tidy = FALSE}
knitr::opts_chunk$set(message = F, error = F, warning = F, comment = NA, fig.align = 'center', dpi = 100, fig.width=6, fig.height=5, tidy = F, cache.path = '1_Line_Plots_cache/', fig.path = '1_Line_Plots/')
```
I recently teamed up with [Mauricio Vargas Sepúlveda](http://pachamaltese.github.io/) to create some graphing tutorials in R. In the coming weeks, we will be publishing a series of tutorials on how to use the `ggplot2` package to create beautiful and informative data visualisations. Each tutorial will explain how to create a different type of plot, and will take you step-by-step from a basic plot to a highly customised graph.
In this first tutorial, we will demonstrate some of the many options the `ggplot2` package has for creating and customising line plots. We will use an international trade [dataset](http://pachamaltese.github.io/stats/trade-chile-china/copper-data-for-tutorial.csv ) made by ourselves from different sources (Chile Customs, Central Bank of Chile and General Directorate of International Economic Relations).
In this tutorial, we will work towards creating the line plot below. We will take you from a basic line plot and explain all the customisations we add to the code step-by-step.
```{r line_final, echo=FALSE, cache=TRUE}
library(ggplot2)
library(ggthemes)
library(extrafont)
charts.data.2 <- read.csv("copper-data-for-tutorial.csv")
charts.data.2 <- as.data.frame(charts.data.2)
charts.data.2$product <- factor(charts.data.2$product, levels = c("copper","others"),
labels = c("Copper ","Pulp wood, Fruit, Salmon & Others"))
colour <- c("#40b8d0", "#b2d183")
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5,
data = charts.data.2, stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_colour_manual(values=colour) +
theme(panel.border = element_rect(colour = "black", fill=NA, size=.5),
axis.text.x=element_text(colour="black", size = 10),
axis.text.y=element_text(colour="black", size = 10),
legend.key=element_rect(fill="white", colour="white"),
legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank(),
panel.grid.major = element_line(colour = "#d3d3d3"),
panel.grid.minor = element_blank(),
panel.border = element_blank(), panel.background = element_blank(),
plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
text=element_text(family="Tahoma"))
p1
```
The first thing to do is load in the data and the libraries, as below:
```{r line_load, cache=TRUE}
library(ggplot2)
library(ggthemes)
library(extrafont)
charts.data <- read.csv("copper-data-for-tutorial.csv")
```
# Basic graph
In order to initialise a plot we tell ggplot that `charts.data` is our data, and specify the variables on each axis. We then instruct ggplot to render this as a line plot by adding the `geom_line` command.
```{r line_1, cache=TRUE}
p1 <- ggplot() + geom_line(aes(y = export, x = year, colour = product),
data = charts.data, stat="identity")
p1
```
# Adjusting line width
To change the line width, we add a `size` argument to `geom_line`.
```{r line_2, cache=TRUE}
p1 <- ggplot() + geom_line(aes(y = export, x = year, colour = product), size=1.5,
data = charts.data, stat="identity")
p1
```
# Changing variables display
To change the variables displayed name, we need to re-factor our data labels in `charts.data` data frame. Then we move the legend to the bottom using the `theme` command.
```{r line_3, cache=TRUE}
charts.data <- as.data.frame(charts.data)
charts.data$product <- factor(charts.data$product, levels = c("copper","others"),
labels = c("Copper ","Pulp wood, Fruit, Salmon & Others"))
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5, data = charts.data, stat="identity") +
theme(legend.position="bottom", legend.direction="horizontal", legend.title = element_blank())
p1
```
# Adjusting x-axis scale
To change the axis tick marks, we use the `scale_x_continuous` and/or `scale_y_continuous` commands.
```{r line_4, cache=TRUE}
p1 <- p1 + scale_x_continuous(breaks=seq(2006,2014,1))
p1
```
# Adjusting axis labels & adding title
To add a title, we include the option `ggtitle` and include the name of the graph as a string argument, and to change the axis names we use the `labs` command.
```{r line_5, cache=TRUE}
p1 <- p1 + ggtitle("Composition of Exports to China ($)") +
labs(x="Year", y="USD million")
p1
```
# Adjusting color palette
To change the colours, we use the `scale_colour_manual` command.
```{r line_6, cache=TRUE}
colour <- c("#5F9EA0", "#E1B378")
p1 <- p1 + scale_colour_manual(values=colour)
p1
```
# Using the white theme
We'll start using a simple theme customisation made adding `theme_bw() ` after `ggplot()`. That theme argument can be modified to use different themes.
```{r line_7, cache=TRUE}
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5,
data = charts.data, stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_colour_manual(values=colour) +
theme_bw() +
theme(legend.position="bottom",
legend.direction="horizontal",
legend.title = element_blank())
p1
```
# Creating an XKCD style chart
Of course, you may want to create your own themes as well. `ggplot2` allows for a very high degree of customisation, including allowing you to use imported fonts. Below is an example of a theme Mauricio was able to create which mimics the visual style of [XKCD](http://xkcd.com/). In order to create this chart, you first need to import the XKCD font, and load it into R using the `extrafont` package.
```{r line_8, cache=TRUE}
fill <- c("#40b8d0", "#b2d183")
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5,
data = charts.data, stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_color_manual(values=fill) +
theme_bw() +
theme(axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
axis.text.x=element_text(colour="black", size = 10),
axis.text.y=element_text(colour="black", size = 10),
legend.key=element_rect(fill="white", colour="white"),
legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), panel.border = element_blank(),
panel.background = element_blank(),
plot.title=element_text(family="xkcd-Regular"),
text=element_text(family="xkcd-Regular"))
p1
```
# Using 'The Economist' theme
There are a wider range of pre-built themes available as part of the `ggthemes` package (more information on these [here](https://cran.r-project.org/web/packages/ggthemes/vignettes/ggthemes.html)). Below we've applied `theme_economist()`, which approximates graphs in the Economist magazine. It is also important that the font change argument inside `theme` is optional and it's only to obtain a more similar result compared to the original. For an exact result you need 'Officina Sans' which is a commercial font and is available [here](http://www.myfonts.com/fonts/itc/officina-sans/).
```{r line_9, cache=TRUE, eval=TRUE}
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5, data = charts.data,
stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
theme_economist() + scale_colour_economist() +
theme(axis.line.x = element_line(size=.5, colour = "black"),
legend.position="bottom",
legend.direction="horizontal",
legend.title = element_blank(),
plot.title=element_text(family="OfficinaSanITC-Book"),
text=element_text(family="OfficinaSanITC-Book"))
p1
```
# Using 'Five Thirty Eight' theme
Below we've applied `theme_fivethirtyeight()`, which approximates graphs in the nice [FiveThirtyEight](http://fivethirtyeight.com/) website. Again, it is also important that the font change is optional and it's only to obtain a more similar result compared to the original. For an exact result you need 'Atlas Grotesk' and 'Decima Mono Pro' which are commercial font and are available [here](https://commercialtype.com/catalog/atlas) and [here](https://www.myfonts.com/fonts/tipografiaramis/decima-mono-pro/).
```{r line_10, cache=TRUE, eval=TRUE}
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5, data = charts.data,
stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
theme_fivethirtyeight() + scale_colour_fivethirtyeight() +
theme(axis.title = element_text(family="Atlas Grotesk Regular"),
legend.position="bottom", legend.direction="horizontal",
legend.title=element_blank(),
plot.title=element_text(family="Atlas Grotesk Medium"),
legend.text=element_text(family="Atlas Grotesk Regular"),
text=element_text(family="DecimaMonoPro"))
p1
```
# Creating your own theme
As before, you can modify your plots a lot as `ggplot2` allows many customisations. Here we present our original result shown at the top of page.
```{r line_11, cache=TRUE}
colour <- c("#40b8d0", "#b2d183")
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5,
data = charts.data, stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_colour_manual(values=colour) +
theme(panel.border = element_rect(colour = "black", fill=NA, size=.5),
axis.text.x=element_text(colour="black", size = 10),
axis.text.y=element_text(colour="black", size = 10),
legend.key=element_rect(fill="white", colour="white"),
legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank(),
panel.grid.major = element_line(colour = "#d3d3d3"),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
text=element_text(family="Tahoma"))
p1
```