-
Notifications
You must be signed in to change notification settings - Fork 3
/
ggplot_cheatsheet.Rmd
78 lines (57 loc) · 2.18 KB
/
ggplot_cheatsheet.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
## Common `ggplot2` solutions
Items from my `ggplot2` cheatsheet (relatively common tasks I can never remember the syntax for). **Note:** I have not updated this since the `ggplot2` version 2.0 release!
### Rotating axis labels
```r
+ theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0))
```
### Getting rid of background color in facet labels
```r
+ theme(strip.background = element_rect(fill = NA))
```
### Scale formatting
```r
+ scale_x_continuous(labels = percent_format()) # or date_format() or comma_format()
```
### Including 0 on an axis
```r
+ expand_limits(y = 0)
```
### Font changes
For most fonts, you'll need the `extrafont` package loaded. The font you specify needs to match the vector returned by `fonts()`.
```r
+ theme(text = element_text(family = "Frutiger LT Std 45 Light"))
```
### Arranging multiple plots
```r
grid.arrange(p1, p2, ncol = 1, heights = c(3, 1)) # p1 on top of p2, p1 3 times taller
# Can be nested with arrangeGrob() for more complicated layouts
grid.arrange(p1, arrangeGrob(p2, p3, ncol = 1), ncol = 2, widths = c(1, 1.2))
# Alternatively, the wq package has a function layOut (notice the capital O)
# which works somewhat similarly to base::layout
# Imagine we want a layout with a 4 plots, a big p1, smaller
# p2 and p3 to the right and thin p4 across the bottom.
# p1 p1 p1 p2
# p1 p1 p1 p2
# p1 p1 p1 p3
# p4 p4 p4 p3
require(wq)
layOut(list(p1, 1:3, 1:3), # plot p1 fills rows 1:3 and columns 1:3
list(p2, 1:2, 4), # plot p2 fills rows 1:2 and column 4
list(p3, 3:4, 4), # plot p3 fills rows 3:4 and column 4
list(p4, 4, 1:3)) # plot p4 fills row 4 and columns 1:3
```
### Legend stuff
```r
+ theme(legend.position = c(0.5, 0.1)) # relative placement, also "none", "top", "left", etc.
+ guides(colour = guide_legend(override.aes = list(alpha = 1))) # overriding alpha (works for colour in a fill legend)
+ guides(colour = guide_legend(reverse = T)) # reverse the order of the legend
# See ?guide_legend for many more options
```
### Adding labels to contour plots
```
volcano3d <- melt(volcano)
v <- ggplot(volcano3d, aes(x, y, z = z)) +
stat_contour(aes(colour = ..level..))
library(directlabels)
direct.label(v2)
```