Skip to content

Lesson 5 Exercise Questions: ggplot2

  1. 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
    

  2. 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.

    Solution

    ggplot(mpg)+
      geom_boxplot(aes(class,hwy))
    

  3. Fill each box with color by class.

    Solution

    ggplot(mpg)+
      geom_boxplot(aes(class,hwy,fill=class))
    

  4. Reorder the boxes by the median of hwy. Hint: See fct_reorder() from forcats. 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")
    

  5. Visualize question two as a violin plot instead.

    Solution

    ggplot(mpg)+
      geom_violin(aes(class,hwy))
    

  6. Visualize a cars engine size in liters (displ) versus fuel efficiency on the hwy (hwy).

    Solution

    ggplot(mpg) +
      geom_point(aes(displ,hwy))
    

  7. 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))
    

  8. 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)