Factors and how to create them
Working with factors
12. Making a bar plot from factors
Modifying factor variables
Summary

Instruction

It would be nice to make a simple bar chart showing the number of people in each age group. We will use the ggplot package to do this. Here's what the code looks like:

ggplot(survey, aes(age)) +
    geom_bar() + coord_flip()

If you're not familiar with ggplot, this code probably looks a bit confusing. However, you should trust that it will create a bar chart of our age groups. Here's a quick overview of what each command does:

  • ggplot() initializes a ggplot object, such as our bar plot. The arguments are the dataset (survey) and aes(), which tells R what coordinates to plot.
  • geom_bar() specifies that this object is a bar plot.
  • coord_flip() creates a horizontal bar chart.

To learn more about creating charts in R with ggplot, check out our Data Visualization 101 course.

Exercise

Plot the number of people in each marital status group using ggplot() and geom_bar(). Use the mrt_status column from survey. Is this plot very informative?

Stuck? Here's a hint!

Type:

ggplot(survey, aes(mrt_status)) + 
    geom_bar() + coord_flip()