Lesson 1 Exercise Questions: ggplot2 basics
These exercise questions should be attempted after completing Lesson 1: Introduction to ggplot2 for R Data Visualization.
Q1: What geoms would you use to draw each of the following named plots?
a. Scatterplot
b. Line chart
c. Histogram
d. Bar chart
e. Pie chart
(Question taken from https://ggplot2-book.org/individual-geoms.html.)
Q1: Solution
a. geom_point
b. geom_line
c. geom_histogram
d. geom_bar
c. geom_bar with coord_polar
Q2. We will use the mpg data set for the remainder of the questions. Use ?mpg to learn more about these data. Visualize highway miles per gallon (hwy) by the class of car using a box plot.
Q2: Solution
library(ggplot2)
ggplot(mpg)+
geom_boxplot(aes(class,hwy))

Q3. Using the plot from Q2, fill each box with color by class.
Q3: Solution
ggplot(mpg)+
geom_boxplot(aes(class,hwy,fill=class))

Q4. Challenge Question: Using the plot from Q3, reorder the boxes by the median of hwy. Hint: See fct_reorder() from forcats.
Q4: Solution
library(forcats)
ggplot(mpg)+
geom_boxplot(aes(fct_reorder(factor(class),hwy,median),hwy,fill=class))

Q5. Visualize highway miles per gallon (hwy) by the class of car using a violin plot.
Q5: Solution
ggplot(mpg)+
geom_violin(aes(class,hwy))

Q6. Visualize a cars engine size in liters (displ) versus fuel efficiency on the hwy (hwy) using a scatter plot.
Q6: Solution
ggplot(mpg) +
geom_point(aes(displ,hwy))

Q7. Using the plot generated in Q6, fit a smooth line (loess) to the data. Color the points by car class.
Q7: Solution
ggplot(mpg) +
geom_point(aes(displ,hwy,color=class))+
geom_smooth(aes(displ,hwy))
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Q8. Visualize a histogram of hwy and facet by year. What is bindwidith (See ?geom_histogram)? Explore the binwidth and color the bars red with a black outline.
Q8: Solution
ggplot(mpg)+
geom_histogram(aes(hwy),fill="red",color="black", binwidth=5) +
facet_wrap(~year)
