-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy path3_Bar_Plots_pdf.Rmd
273 lines (220 loc) · 12.7 KB
/
3_Bar_Plots_pdf.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
---
title: "Creating plots in R using ggplot2 - part 3: bar plots"
author:
- Jodie Burchell
- Mauricio Vargas Sepúlveda
date: "`r Sys.Date()`"
output:
pdf_document:
keep_tex: yes
toc: yes
---
```{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 = 96, fig.width=6, fig.height=5, tidy = F, cache.path = '3_Bar_Plots_cache_pdf/', fig.path = '3_Bar_Plots_pdf/', dev = 'quartz_pdf', dev.args=list(pointsize=12))
```
In this third tutorial I am doing with [Mauricio Vargas Sepúlveda](http://pachamaltese.github.io/), we will demonstrate some of the many options the ggplot2 package has for creating and customising bar plots. We will use the same [dataset](http://pachamaltese.github.io/stats/trade-chile-china/copper-data-for-tutorial.csv) from the [first](http://t-redactyl.github.io/blog/2015/12/creating-plots-in-r-using-ggplot2-part-1-line-plots.html) post.
In this tutorial, we will work towards creating the area plot below. We will take you from a basic bar plot and explain all the customisations we add to the code step-by-step.
```{r bar_final, echo=FALSE, cache=TRUE}
library(ggplot2)
library(ggthemes)
library(extrafont)
library(plyr)
library(scales)
charts.data <- read.csv("copper-data-for-tutorial.csv")
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"))
charts.data <- ddply(charts.data, .(year), transform, pos = cumsum(export) - (0.5 * export))
fill <- c("#40b8d0", "#b2d183")
p3 <- ggplot() +
geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export), colour="black",
family="Tahoma", size = 4, show.legend = F) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_fill_manual(values=fill) +
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"))
p3
```
# Basic graph
The first thing to do is load in the data and the libraries, as below:
```{r bar_load_in_data, cache=TRUE}
library(ggplot2)
library(ggthemes)
library(extrafont)
library(plyr)
library(scales)
charts.data <- read.csv("copper-data-for-tutorial.csv")
```
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 an bar plot by adding the `geom_area` command.
```{r bar_1, cache=TRUE}
p3 <- ggplot() + geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity")
p3
```
# Adding data labels
To label the bars according to some variable in the data, we add the `label` argument to the `ggplot(aes())` option. In this case, we have labelled the bars with numbers from the `export` variable.
```{r bar_2, cache=TRUE}
p3 <- p3 + geom_text(data=charts.data, aes(x = year, y = export, label = export), size=4)
p3
```
# Adjusting data labels position
To adjust the position of the data labels from the default placement, we use the `ddply` function on the data, and create a new variable called `pos`. This variable is at the centre of each bar and can be used to specify the position of the labels by assigning it to the `y` argument in `geom_text(aes())`.
```{r bar_3, cache=TRUE}
charts.data <- ddply(charts.data, .(year), transform, pos = cumsum(export) - (0.5 * export))
p3 <- ggplot() + geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity")
p3 <- p3 + geom_text(data=charts.data, aes(x = year, y = pos, label = export), size=4)
p3
```
# Adjusting legend position
To adjust the position of the legend from the default spot of right of the graph, we add the `theme` option and specify the `legend.position="bottom"` argument. We can also change the title to blank using the ` legend.title = element_blank()` argument and change the legend shape using the `legend.direction="horizontal"` argument.
```{r bar_4, cache=TRUE}
p3 <- p3 + theme(legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank())
p3
```
# Changing variables display
To change the variables' displayed name, we need to re-factor our data labels in `charts.data` data frame.
```{r bar_5, cache=TRUE, eval=TRUE}
charts.data$product <- factor(charts.data$product, levels = c("copper","others"),
labels = c("Copper ","Pulp wood, Fruit, Salmon & Others"))
p3 <- ggplot() + geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export, size=4),
show.legend = F) +
theme(legend.position="bottom", legend.direction="horizontal", legend.title = element_blank())
p3
```
# Adjusting x-axis scale
To change the axis tick marks, we use the `scale_x_continuous` and/or `scale_y_continuous` commands.
```{r bar_6, cache=TRUE}
p3 <- p3 + scale_x_continuous(breaks=seq(2006,2014,1))
p3
```
# 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 bar_7, cache=TRUE}
p3 <- p3 + ggtitle("Composition of Exports to China ($)") + labs(x="Year", y="USD million")
p3
```
# Adjusting color palette
To change the colours, we use the `scale_colour_manual` command. Note that you can reference the specific colours you'd like to use with specific HEX codes. You can also reference colours by name, with the full list of colours recognised by R [here](http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf).
```{r bar_8, cache=TRUE}
fill <- c("#5F9EA0", "#E1B378")
p3 <- p3 + scale_fill_manual(values=fill)
p3
```
# Using the white theme
As explained in the previous posts, we can also change the overall look of the graph using themes. We'll start using a simple theme customisation by adding `theme_bw() ` after `ggplot()`. As you can see, we can further tweak the graph using the `theme` option, which we've used so far to change the legend.
```{r bar_9, cache=TRUE}
p3 <- ggplot() +
geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export, size=4), show.legend = F) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_fill_manual(values=fill) +
theme_bw() +
theme(legend.position="bottom",
legend.direction="horizontal",
legend.title = element_blank())
p3
```
# 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 bar_10, cache=TRUE}
fill <- c("#40b8d0", "#b2d183")
p3 <- ggplot() +
geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export), colour="black",
family="xkcd-Regular", size = 4, show.legend = F) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_fill_manual(values=fill) +
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"))
p3
```
# 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 bar_11, cache=TRUE}
p3 <- ggplot() +
geom_bar(aes(y = export, x = year, fill = product), data = charts.data,
stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export), colour="white", size = 4, family = "OfficinaSanITC-Book", show.legend = F) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
theme_economist() + scale_fill_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"))
p3
```
# 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 bar_12, cache=TRUE}
p3 <- ggplot() +
geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export), colour="white", size = 3.5, family = "DecimaMonoPro-Bold", show.legend = F) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
theme_fivethirtyeight() + scale_fill_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"))
p3
```
# 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 bar_13, cache=TRUE}
fill <- c("#40b8d0", "#b2d183")
p3 <- ggplot() +
geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export), colour="black",
family="Tahoma", size = 4, show.legend = F) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_fill_manual(values=fill) +
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"))
p3
```