2 · Visualize (exercises) — source
This page shows the source file of the exercise below. Use the button to download it as a plain file and run it in your own workspace.
---
title: "Visualize Data"
format:
html:
eval: false
---
## Your Turn 0
Add a setup chunk that loads the tidyverse packages and turn the global option
`eval` to `true` in the above YAML header.
```ltd
mpg
```
## Your Turn 1
Run the code on the slide to make a graph. Pay strict attention to spelling,
capitalization, and parentheses!
```ltd
```
## Your Turn 2
Add `color`, `size`, `alpha`, and `shape` aesthetics to your graph. Experiment.
```ltd
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
```
## Help Me
What do `facet_grid()` and `facet_wrap()` do?
(run the code, interpret, convince your group)
```ltd
# Makes a plot that the commands below will modify
q <- ggplot(mpg) + geom_point(aes(x = displ, y = hwy))
q + facet_grid(cols = vars(cyl))
q + facet_grid(rows = vars(drv))
q + facet_grid(rows = vars(drv), cols = vars(cyl))
q + facet_wrap(facets = vars(class))
```
## Your Turn 3
Add the black code to your graph. What does it do?
```ltd
ggplot(data = mpg) +
geom_point(mapping = aes(displ, hwy, color = class))
```
## Your Turn 4
Replace this scatterplot with one that draws boxplots. Use the cheatsheet. Try
your best guess.
```ltd
ggplot(mpg) + geom_point(aes(class, hwy))
```
## Your Turn 5
Make a histogram of the `hwy` variable from `mpg`. Hint: do not supply a y
variable.
```ltd
```
## Your Turn 6
Use the help page for `geom_histogram` to make the bins 2 units wide.
```ltd
```
## Your Turn 7
Make a bar chart `class` colored by `class`. Use the help page for `geom_bar` to
choose a "color" aesthetic for class.
```ltd
```
## Quiz
What will this code do?
```ltd
ggplot(mpg) +
geom_point(aes(displ, hwy)) +
geom_smooth(aes(displ, hwy))
```
## Quiz
What is different about this plot? Run the code!
```ltd
p <- ggplot(mpg) +
geom_point(aes(displ, hwy)) +
geom_smooth(aes(displ, hwy))
library(plotly)
ggplotly(p)
```
***
# Take aways
You can use this code template to make thousands of graphs with **ggplot2**.
```ltd
#| eval: false
ggplot(data = <DATA>) +
<GEOM_FUNCTION>(mapping = aes(<MAPPINGS>))
```