-
Notifications
You must be signed in to change notification settings - Fork 6
/
ggplot_tutorial.Rmd
289 lines (201 loc) · 9.11 KB
/
ggplot_tutorial.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
Introduction to ggplot2
=======================
```{r}
library(ggplot2)
library(reshape2)
```
Basic plotting
--------------
`qplot()` is ggplot2's equivalent of `plot()`
```{r fig.width=8, fig.height=5}
qplot(x=iris$Petal.Width, y=iris$Petal.Length,
colour=iris$Species, geom='point')
```
Produces the same results as
```{r fig.width=8, fig.height=5, fig.keep='none'}
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, colour=Species)) + geom_point()
```
This command consists of three main components:
* The data, `iris`, which is `dataframe` (or a sub-class, like `data.table`).
* A set of mappings from columns of the data set, `aes(...)`.
* A geometry, `geom_histogram()`.
What's going on?
----------------
ggplot2's language is based on the "Grammar of graphics" (Wilkinson 1999).
Every plot consists of a background, and one or more of each of the following:
* **Layers** - sets of data (from a `dataframe` or `data.table`) with mappings, scales, geometries and statistics applied. Data needs to be in 'long; format - one
* **Aesthetic mappings** - conversion from a data variable (Sepal.Width, ...) to a visual variable (x, y, colour, size, ...).
* **Scales** - functions, limits, and divisions of the visual variables (logarithmic x-axis, colours gradients, y-axis division lines, ...).
* **Geoms** - methods of plotting the data (points, lines, boxplots, ...).
* **Statistics** - conversions between the raw data and some visual summary (**identity**, binning, quantiles, smoothers, ...)
Most geoms are actually a shortcut for a set of default scales, lower-level geometries, and statistics. Most statistics have default geoms. Each of these automatically set up a layer, so you don't have to specify it manually.
There are also a few other components that pop up less frequently, including coordinate systems (e.g. polar plots), positions (fine tuning of object positioning), facets (small-multiple plotting), and themes (that control various graphical aspects of the whole plot).
There is a full list of available geoms, stats, etc. at http://docs.ggplot2.org/current/ .
Also, all ggplot functions have good built-in docs, which list the default stats for geoms, etc.
### Example
We can create histograms similarly to the plots up the top:
```{r fig.width=8, fig.height=5}
ggplot(data=iris, aes(x=Petal.Width, fill=Species)) + geom_histogram(binwidth=0.2)
```
What's happening:
* We're using `iris` as our main data source.
* We're using the histogram geom.
* geom_histogram uses `stat_bin()` as it's default statistic.
* `stat_bin` puts up a warning about binwidth if you don't include the `binwidth` parameter. geom_histogram helpfully passes it along.
* We're mapping the x axis to `Petal.Width` in the `iris` dataframe.
* geom_histogram handles the mapping from the y axis to the counts for each bin from `stat_bin()`.
* We're mapping the colour of the bars (actually geom_rectangles in disguise) to the Species in `iris`.
* geom_histogram uses `position_stack()` by default, so the colours are stacked.
* ggplot uses linear scales for all continuous/ordinal variables by default. For categorical variables (e.g. Species) it divides the space (e.g. colour==hue) up into equal divisions.
Here is a fully specified version of the plot above:
```{r fig.width=8, fig.height=5, fig.keep='none'}
ggplot() +
layer(data=iris,
mapping=aes(x=Petal.Width,
fill=Species
),
stat='bin',
stat_params=list(binwidth=0.2),
geom='histogram',
geom_params=list(),
position='identity'
) +
scale_x_continuous() +
scale_y_continuous() +
scale_fill_hue() +
coord_cartesian()
```
### Modifying plots
We can change any aspect of this plot, by adding the relevant scales/positions/statistics etc.:
```{r fig.width=8, fig.height=5}
p <- ggplot(iris, aes(x=Petal.Width, fill=Species)) +
geom_histogram(binwidth=0.2, position=position_dodge()) +
scale_fill_manual(values=c('red', 'black', 'green'))
p
```
In the above example, we stored the plot in the variable `p`. We can create variations on the plot by adding more ggplot functions:
```{r fig.width=8, fig.height=5}
p + scale_y_continuous(name='Number of samples') + scale_x_continuous(name="Petal width") + coord_polar()
```
If you add a scale that already exists, the old one gets overwritten (with a warning). So:
```{r fig.width=8, fig.height=5}
p + scale_fill_grey()
```
Facetting
---------
Faceting is a really handy way to create small-multiples sub-plots. There are two options: `facet_grid()`, and `facet_wrap()`.
```{r fig.width=8, fig.height=5}
# help(CO2) # for a description
head(CO2, 3)
ggplot(CO2, aes(y=uptake, x=conc)) + geom_line()
```
Doesn't work because ggplot treats all data as a single set. We can tell it to treat separate groups as subsets:
```{r fig.width=8, fig.height=5}
p <- ggplot(CO2, aes(y=uptake, x=conc, group=Plant)) + geom_line()
p
```
`aes(colour=...)` implies group too, but isn't that useful here:
```{r fig.width=8, fig.height=5}
ggplot(CO2, aes(y=uptake, x=conc, colour=Plant)) + geom_line()
```
Instead, we can create a set of small-multiples over the type and treatment factors:
```{r fig.width=8, fig.height=5}
p + facet_grid(Type ~ Treatment, scale='free_y')
```
Plotting non-dataframe data:
----------------------------
The `volcano` dataset is a matrix of heights:
```{r}
str(volcano)
```
Using `melt()` from the `reshape2` library, we can convert it to a long dataframe:
```{r fig.width=8, fig.height=5}
volc_m <- melt(volcano, varnames=c('lat', 'long'), value.name='height')
str(volc_m)
p_volcano <- ggplot(volc_m, aes(x=lat, y=long, fill=height)) + geom_tile()
p_volcano
```
Poor colours, we can improve those:
```{r fig.width=8, fig.height=5}
p_volcano + scale_fill_gradientn(colours=terrain.colors(10))
```
We could also add some contour lines:
```{r fig.width=8, fig.height=5}
p_volcano + scale_fill_gradientn(colours=terrain.colors(10)) +
geom_contour()
```
Doesn't work, because we haven't provided a mapping for z - the apparent "height" of the tiles was defined by fill colour, not z. So we add another mapping:
```{r fig.width=8, fig.height=5}
p_volcano + scale_fill_gradientn(colours=terrain.colors(10)) +
geom_contour(mapping=aes(z=height), colour='black')
```
This mapping only applies to the stat_contour. We could also have added it to the original `ggplot(aes(...))`, and it would apply to all layers/geoms (which wouldn't change anything in this case, because `geom_tile` doesn't have a z variable).
#### Converting from wide-format dataframes:
From wide data: USJudgeRatings:
```{r}
head(USJudgeRatings, 3)
# convert row names to a data frame variable
USJudgeRatings$name <- rownames(USJudgeRatings)
head(USJudgeRatings, 3)
# Just use a subset for a simpler plot
USJR_melt <- melt(USJudgeRatings[,])
head(USJR_melt, 3)
```
Now we can plot it!
```{r fig.width=10, fig.height=7}
ggplot(USJR_melt, aes(x=variable, y=value, colour=value)) +
geom_point() +
geom_line(aes(x=as.integer(variable))) +
scale_colour_gradientn(colours=heat.colors(5)) +
facet_wrap('name', ncol=5) +
theme_bw() +
theme(axis.text.x=element_text(angle=-90))
```
`theme()` lets you pass various options to control global plotting variables. `help(theme)` has a big list of them.
Positions
----------
```{r fig.width=8, fig.height=5}
p_mpg <- ggplot(mpg, aes(x=hwy, y=cty, colour=displ))
p_mpg + geom_point()
```
Some overlap here, so we can add some jitter:
```{r fig.width=8, fig.height=5}
p_mpg + geom_point(position=position_jitter())
```
Could also plot the density:
```{r fig.width=8, fig.height=5}
p_mpg + geom_point(position=position_jitter()) +
geom_density2d(colour='black', alpha=0.3)
```
#### Smoothing
It might be more helpful to just plot points and an average here:
```{r fig.width=8, fig.height=5}
# leave group out, so that the smoother uses all data:
p <- ggplot(CO2, aes(y=uptake, x=conc)) + geom_point() +
facet_grid(Type ~ Treatment)
p + stat_smooth() # geom_smooth does the same thing there: same defaults
```
That smoother is the default, which is loess. Loess can be a little too detailed though, and it's possible to pass any smoother, for instance, `lm`:
```{r fig.width=8, fig.height=5}
p <- ggplot(CO2, aes(y=uptake, x=conc)) + geom_point() +
facet_grid(Type ~ Treatment)
p + stat_smooth(method='lm')
```
Probably not enough detail. How about just the mean at each concentration, plus a standard deviation?
```{r fig.width=8, fig.height=5}
# from http://stackoverflow.com/questions/12033319
p + stat_summary(fun.y = 'mean', colour = 'blue', geom = 'line') +
stat_summary(fun.data = 'mean_cl_normal', geom = 'ribbon', alpha = 0.25)
```
Mapping
-------
Mapping can be done over the top of google maps with the `ggmap` package.
```{r fig.width=8, fig.height=5}
# based on http://stackoverflow.com/questions/10302195
library(ggmap)
quakes_map <- get_map(location=c(lon=mean(quakes$lon), lat=mean(quakes$lat)), zoom = 5, maptype = 'satellite')
ggmap(quakes_map) +
geom_point(data=quakes, mapping=aes(x=long, y=lat, size=mag, colour=depth)) +
scale_colour_gradientn(colours=heat.colors(5))
```
You can add`coord_map()` to use different map projections, but it doesn't play well with ggmap by default.