Lesson 5 Exercise Questions: ggplot2
-
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.)
Solution
a. geom_point b. geom_line c. geom_histogram d. geom_bar c. geom_bar with coord_polar -
We will use the
mpgdata set for the remainder of the questions. Use?mpgto learn more about these data. Visualize highway miles per gallon (hwy) by the class of car using a box plot.Solution
ggplot(mpg)+ geom_boxplot(aes(class,hwy)) -
Fill each box with color by
class.Solution
ggplot(mpg)+ geom_boxplot(aes(class,hwy,fill=class)) -
Reorder the boxes by the median of
hwy. Hint: Seefct_reorder()fromforcats. Change the x and y labels.Solution
ggplot(mpg)+ geom_boxplot(aes(fct_reorder(factor(class),hwy,median),hwy,fill=class))+ labs(y="Miles per gallon (hwy)", x="Vehicle Class") -
Visualize question two as a violin plot instead.
Solution
ggplot(mpg)+ geom_violin(aes(class,hwy)) -
Visualize a cars engine size in liters (
displ) versus fuel efficiency on the hwy (hwy).Solution
ggplot(mpg) + geom_point(aes(displ,hwy)) -
Fit a smooth line (loess) to the data from question 6. Color the points by car class.
Solution
ggplot(mpg) + geom_point(aes(displ,hwy,color=class))+ geom_smooth(aes(displ,hwy)) -
Visualize a histogram of hwy and facet by year. Explore the binwidth and color the bars red with a black outline.
Solution
ggplot(mpg)+ geom_histogram(aes(hwy),fill="red",color="black", binwidth=5) + facet_wrap(~year)