Repository navigation
Expand file tree
/
Copy path06-graphics.Rmd
More file actions
213 lines (167 loc) · 7.4 KB
/
Copy path06-graphics.Rmd
File metadata and controls
213 lines (167 loc) · 7.4 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
204
205
206
207
208
209
210
211
212
213
# Base graphics
## Basic constructions and scatter plots
We have already seen how to add a line to a scatter plot, to complete the graph we can specify a title, change the axis labels, and add a legend:
```{r}
plot(wt, mpg,
main = 'Weight and consumption of cars',
xlab = 'weight', ylab = 'consumption') # xlab = label x axis
abline(h = mean (mpg), col = 2, lty = 2) # h = horizontal line, col = color, lty = line type
legend(x = 'topright', lty = 2, col = 2, legend = 'average consumption')
# x = legend location
```
We can also add a third dimension by coloring the points according to a condition:
```{r}
plot(wt, mpg,
pch = 19, # pch = type of point
col = (mpg >= mean (mpg)) + 1 # 1 = black, 2 = red
)
abline(h = mean(mpg), col = 2, lty = 2) # h = horizontal line, col = color, lty = line type
legend(x = 'topright',
pch = 19,
col = 2: 1,
legend = c ('cons> = average', 'cons <average'), # legend = vector with labels
bty = 'n' # no frame around the legend
)
```
In general, `abline(a, b)` allows to add a line with intercept `a` and slope` b` to an existing plot. For example, an alternative way to add the regression line is as follows:
```{r, eval = FALSE}
intercept = coef(m)[1]
slope = coef(m)[2]
plot(wt, mpg, main = 'Line of least squares')
abline(a = intercept, b = slope)
```
To add any line (not necessarily a straight line) we use the `lines()` function. For example, to add the _lowess_ (locally-weighted polynomial regression) smoothing curve:
```{r}
plot(wt, mpg, main = 'Smoothing curve')
lines(lowess (mpg ~ wt), # lines (): to add a curve
col = 'blue', # same as col = 4
lwd = 2) # lwd = line thickness
```
We can add new points using `points()`:
```{r}
plot(wt, mpg, main = 'Smoothing curves')
lines(lowess (mpg ~ wt), col = 'blue', lwd = 2)
outliers = cbind(c(4.5,4.6,5), c(26,26,30))
points(outliers, pch = 2) # pch = 2 for triangles
lines(lowess (c (wt, outliers[, 1]),
c (mpg, outliers[, 2])),
col = 2, lwd = 2)
legend (x = 'bottomleft', col = c (4,2), lwd = 2, legend = c ('without outliers', 'with outliers'), bty = 'n')
```
We can control the range of axes using `xlim()` and `ylim()`:
```{r}
plot(wt, mpg, main = 'Same data with different scale',
xlim = c (0, 25),
ylim = c (0, 100))
```
## Line graphs
The `lines()` function adds a line to an existing graph and cannot be used to create a new graph. To draw a line connecting the successive elements of a vector we will rather use `plot(x = vector, type = l)`:
```{r}
mydata = cos(2 * pi / 12 * (1:36)) + rnorm (36,0, .2) # data simulation
plot(mydata, type = 'l', main = 'type = l')
```
The `type` parameter allows you to connect (or not) the points in different ways:
```{r}
par(mfrow = c (2,2)) # explained in the next section
plot(mydata, type = 'p', main = 'type = p') # default
plot(mydata, type = 'o', main = 'type = o')
plot(1: 10, type = 'S', main = 'type = S') # steps 1
plot(1: 10, type = 's', main = 'type = s') # steps 2
```
With `plot = 'h'` we get a bar plot:
```{r}
plot (1: 10, type = 'h', main = 'type = h')
```
## Graphical parameters
We have already seen that it is possible to control certain graphical elements using parameters:
Element | Parameter
------- | ---------
point | `pch`
type of line graph | `type`
color | `col`
line | `lty`,` lwd`
axis label | `xlab`,` ylab`
axis dimensions | `xlim`,` ylim`
label dimensions | `cex`
orientation axes labels | `las`
See `?par` for a description of the values that these parameters can take.
To impose parameters on all the graphics produced during a session, we will use the `par()` function. `par()` is often used to view two or more plots in the same window with the parameter `mfrow = c(l, c)`. In this case the graphs are displayed in a grid with `l` rows and `c` columns. Try the following:
```{r}
# opar = par () # to be able to reset with the initial parameters
par(mfrow = c (1,2))
plot(wt, mpg, main = 'Weight, consumption')
boxplot(hp, main = 'Power')
```
Changes are implemented until when the session is closed, or the graphics engine is reset by `dev.off()` or by clicking on the `Clear all plots` brush in `RStudio`.
`par()` is also used to change the size of the margins. This is sometimes useful when the labels on the axes do not fit in the window, as in this example:
```{r}
mydata = as.factor(sample (x = c ('Paris', 'London', 'Brussels', 'Washington'),
replace = T,
prob = c (.1, .5, .2, .1),
size = 100)) # simulation of a qualitative variable
barplot(summary (mydata),
width = .1,
horiz = T,
las = 2)
```
We modify the parameter which sets the left margin:
```{r}
par(mar = c(5, 6, 4, 2) + 0.1) # the second component of mar gives the left margin
# Default is c (5, 4, 4, 2) + 0.1
barplot(summary (mydata),
width = .1,
horiz = T,
las = 2)
```
## Histograms
As we have already noted in the subsection \@ref(quant-var), by default, `hist()` displays the histogram with the counts. To display the histogram in the density scale we use the option `freq = FALSE`. In this case, the area of each rectangle will be equal to the proportion of observations in the corresponding class (so that the total area of all the rectangles is one).
```{r, eval = FALSE}
par(mfrow = c (1,2))
hist(mpg) # freq = TRUE
hist(mpg, freq = FALSE)
```
To superimpose the curve of a given density:
```{r}
mydata = rnorm (1000,0,1) # simulation of 1000 observations N (0,1)
hist(mydata, freq = F, main = 'Histogram and theoretical density')
curve(dnorm, # the density function of N (0,1)
from = -5, to = 5, # the range
add = TRUE) # because we want to add the density of N (0,1) to the histogram
```
Rather than viewing the histogram of the data, we can show the estimated density (using kernel density estimation methods):
```{r}
hist(mpg, freq = F, main = 'Histogram and estimated density')
lines(density (mpg), col = 2)
```
## Exercises
1. We consider the `midwest` dataset from the `ggplot2` package (an advanced graphics package).
- Install and charge the package.
- Consult the help for the description of the variables in `midwest`.
- Reproduce the following graphics using basic functions:
```{r,echo=FALSE, warning=FALSE, message=FALSE}
library(ggplot2)
par(mfrow = c(1,2))
plot(midwest$area, midwest$poptotal,
pch = 19,
xlab = 'Surface', ylab='Population',
col = midwest$inmetro+1,
# inmetro=0=rural hence rural=0+1=black
# inmetro=1=urban hence urban=1+1=red
main = 'Counties')
legend(x = 'topleft', pch=19,
col=1:2, legend = c('Rural', 'Urban'),
box.lty=0)
plot(midwest$area, midwest$poptotal,
pch = as.numeric(as.factor(midwest$state)),
col = midwest$inmetro+1,
xlab = 'Surface', ylab='Population',
main = 'Contées américaines')
legend(x = 'topleft', pch=c(1:5,1,1),
col = c(rep(1,5),1:2),
legend = c(levels(as.factor(midwest$state)),'Rural','Urbain'),
box.lty=0)
```
2. We consider the `adult` dataset available on the site [archive.ics.uci.edu/ml/datasets/Adult](https://archive.ics.uci.edu/ml/datasets/Adult). The dataset consists of 48,842 rows and 14 columns.
- Import the data into `R` from the file `adult.data`. Look in the `adult.names` file for the names of the variables.
- Describe each variable appropriately according to its type.
- Describe the relationship between the variables `age` and` class`.