-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathp4c3-plotting.qmd
251 lines (195 loc) · 8.46 KB
/
p4c3-plotting.qmd
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
# Plotting
This chapter will cover the basics of creating plots in R. It will begin by demonstrating the plotting capabilities available in R out of the box. These capabilities are often referred to as "Base R". In the resources section, you can also find resources to learn more about "ggplot2" which is one of the most common plotting libraries in R.
## Plotting your Regression Model
Now that you've learned how create a linear regression model, let's look at how you might go about representing it visually.
Here's a preview of the dataset we'll be using:
```{r}
#| echo: false
#| output: false
x <- c(1:100)
y <- c(-4.400327034,5.428396028,1.401835325,8.347444696,4.653595058,1.768965792,2.301670121,2.906690807,
16.86055207,12.79819406,19.43688567,9.535898321,11.44692921,12.85126784,6.102193819,14.9299838,14.10825511,
9.061679003,15.02212052,18.6447931,17.02989089,18.93455371,31.15646579,21.87836403,19.74845288,26.59660838,
36.50126821,31.89097261,22.11512438,29.18472781,38.72830304,40.13431252,27.21738666,39.88887474,36.23490911,
32.17006556,30.10621489,37.92219413,33.15571816,33.7647255,33.7444351,34.12172411,37.19967163,45.34378315,
35.98530015,53.90675935,50.52742803,46.06208273,57.82271516,55.3300409,42.16904545,52.68638053,54.81650327,
52.07962127,54.82388858,52.96289171,66.86594353,55.91500631,53.46845318,69.93363692,63.77966506,56.9824017,
57.10158014,57.0690513,62.38929311,74.9465375,62.0905341,73.7790738,59.19482129,60.94042919,70.84003803,
75.95901236,81.58801567,74.87006685,78.72743515,83.59639222,80.82508933,76.42767133,71.59042346,83.83529445,
89.09992891,79.91862252,74.4198755,75.99386989,91.45464708,89.15434974,77.38263974,91.69502627,83.96595701,
80.07178088,87.70105337,82.82445978,91.9984167,95.93813464,93.32235278,100.9042819,87.4809175,102.1559695,
106.5412224,94.53627918
)
df <- data.frame(y = y, x = x)
```
```{r}
#| echo: false
knitr::kable(head(df), format="markdown")
```
We'll begin by just creating a scatter plot of the raw data.
```{r}
plot(df$x, df$y)
```
Additionally, you can alter the appearance of your points by using the “pch”, “cex”, and “col” options. PCH stands for Plot Character and will adjust the symbol used for your points. The available point shapes are listed in the image below.
```{r out.extra="style='background-color: #9ecff7; padding:10px; display: block; margin-left: auto; margin-right: auto; width: 80%;'"}
#| warning: false
ggpubr::show_point_shapes()
```
The “cex” option allows you to adjust the symbol size. The default value is 1. If you were to change the value to .75, for example, the plot symbol would be scaled down the 3/4 of the default size. The “col” option allows you to adjust the color of your plot symbols.
```{r}
plot(df$x
, df$y
, col=rgb(0.4,0.4,0.8,0.6)
, pch=16
, cex=1.2)
```
You can adjust the axes with the “xlab”, “ylab”, “xaxt”, and “yaxt” options (amongst other available options). In the following example we will remove the axes altogether.
```{r}
plot(df$x
, df$y
, col=rgb(0.4,0.4,0.8,0.6)
, pch=16
, cex=1.2
, xlab=""
, ylab=""
, xaxt="n"
, yaxt="n")
```
Finally, you can add a trend line by creating a model and adding the fitted values to the graph. We’ll also adjust the line width and color with the “lwd” and “col” parameters, respectively.
```{r}
plot(df$x
, df$y
, col=rgb(0.4,0.4,0.8,0.6)
, pch=16
, cex=1.2
, xlab=""
, ylab=""
, xaxt="n"
, yaxt="n")
model <- lm(df$y ~ df$x)
abline(model, col=2, lwd=2)
```
The model also returns confidence intervals for the predictions, which can
be added
```{r}
# Extract the upper and lower 95% confidence intervals of the predictions
conf_interval <- predict(
model,
newdata=data.frame(x=df$x),
interval = "prediction",
level = 0.95)
plot(df$x
, df$y
, col=rgb(0.4,0.4,0.8,0.6)
, pch=16
, cex=1.2
, xlab=""
, ylab=""
, xaxt="n"
, yaxt="n")
abline(model, col=2, lwd=2)
lines(df$x, conf_interval[,2], col="blue", lty=2)
lines(df$x, conf_interval[,3], col="blue", lty=2)
```
## Plots Available in Base R
Now that you've seen how to build a scatterplot in R, let's take a look at other plots available in Base R.
### Box Plot
One plot you've already seen in the outliers chapter is the box plot. These plots can be created via the "boxplot" function.
```{r}
boxplot(mtcars$mpg)
```
We can build on this plot by specifying the dataset with the "data" parameter, removing the "mtcars$" prefix from our variable, adding a plot title with the "main" parameter, and adding axis labels with the "xlab" and "ylab" parameters. Additionally, we are going to add an additional variable for our data to be categorized by.
```{r}
boxplot(mpg ~ gear
, data = mtcars
, main = "Car Mileage by Gear"
, xlab = "Number of Forward Gears"
, ylab = "Miles Per Gallon")
```
Finally, we can set the box colors with the "col" parameter and set "notch" equal to "TRUE" to give our boxes notches. If the notches of two plots do not overlap this is ‘strong evidence’ that the two medians differ @Chambers83.
```{r}
#| warning: false
boxplot(mpg ~ am
, data = mtcars
, notch = TRUE
, col = (c("blue", "grey"))
, main = "Car Mileage by Engine"
, xlab = "Automatic?"
, ylab = "Miles Per Gallon")
```
### Plot Matrix
You can use the "pairs" function to create a plot matrix. Let's use the iris dataset to demonstrate this.
```{r}
pairs(iris)
```
This plot gives us the ability to see how each variable interacts with one another.
### Pie Chart
Let's try plotting a pie chart of species in the iris dataset via the "pie" function. This function accepts numerical values so we'll need to use the "table" function on our column as well.
```{r}
pie(table(iris$Species))
```
You can view the full list of available parameters for this and other functions through the help tab in the files pane in R Studio.
```{r out.extra="style='background-color: #9ecff7; padding:10px; display: block; margin-left: auto; margin-right: auto; width: 80%;'"}
#| label: plotting-1
#| echo: false
#| out.width: 500
knitr::include_graphics("images/reporting/plotting-1.png", dpi = 270)
```
### Bar Plot
Let's try a bar plot on the same dataset with the "barplot" function.
```{r}
barplot(table(iris$Species))
```
### Histogram
You may recall that we also used histigrams in the outliers chapter to try to visually identify extreme values. Here's a quick recap:
```{r}
hist(mtcars$mpg)
```
### Density Plot
We also used the following example in the outliers chapter to create a density plot:
```{r}
plot(density(mtcars$mpg))
```
We can take this one step further by adding a title and a shape to the plot.
```{r}
mpg <- density(mtcars$mpg)
plot(mpg, main="MPG Distribution")
polygon(mpg, col="lightblue", border="black")
```
### Dot Chart
```{r}
salesperson <- c("Susan", "Taylor", "Steven"
, "Michael", "Reagan", "Michael"
, "Alaka", "Trevor", "Isaac"
, "Jordan", "Aaron", "Miles")
product <- c("Professional Services", "Professional Services"
, "Professional Services", "Professional Services"
, "Software", "Software", "Software", "Software"
, "Hardware", "Hardware", "Hardware", "Hardware")
sales <- c(10, 7, 13, 18, 12, 19, 14, 16, 21, 9, 17, 19)
df <- data.frame(salesperson = salesperson, product = product, sales = sales)
dotchart(df$sales)
dotchart(df$sales, labels = df$salesperson)
groups <- as.factor(df$product)
dotchart(df$sales, labels = df$salesperson, groups = groups)
group_colors <- c("blue", "darkred", "darkgreen")
dotchart(df$sales
, labels = df$salesperson
, groups = groups
, gcolor = group_colors)
dotchart(df$sales
, labels = df$salesperson
, groups = groups
, gcolor = group_colors
, color = group_colors[groups]
, pch = 16)
```
<!--
## ggplot2
One of the most widely used methods for plotting in R is the ggplot2 package.
### Different types of plots? -->
## Resources
- ggplot2 documentation: <https://ggplot2.tidyverse.org/>
- ggplot2 cheat sheet: <https://github.com/rstudio/cheatsheets/blob/main/data-visualization.pdf>
- ggplot2 extension gallery: <https://exts.ggplot2.tidyverse.org/gallery/>
- R colors: <http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf>