Get startedGet started for free

Customizing a ggplot2 margin of error plot

You've hopefully identified some problems with the chart you created in the previous exercise. As the counties are not ordered, patterns in the data are difficult for a viewer to parse. Specifically, margin of error plots are much more effective when dots are ordered as the ordering allows viewers to understand the uncertainty in estimate values relative to other estimates. Additionally, the lack of plot formatting makes it difficult for chart viewers to understand the chart's content. In this exercise, you'll clean up your ggplot2 code to create a much more visually appealing margin of error chart.

This exercise is part of the course

Analyzing US Census Data in R

View Course

Exercise instructions

  • Use the str_replace() tidyverse function to remove " County, Maine" from the county name.
  • Reorder the counties in descending order of median household income in the plot.
  • Set the subtitle to "Counties in Maine" to add information common to the data points with subtitle.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Remove unnecessary content from the county's name
maine_inc2 <- maine_inc %>%
  mutate(NAME = ___(NAME, " County, Maine", ""))

# Build a margin of error plot incorporating your modifications
ggplot(maine_inc2, aes(x = estimate, y = ___(NAME, estimate))) + 
  geom_errorbarh(aes(xmin = ___ - moe, xmax = estimate + ___)) + 
  geom_point(size = 3, color = "darkgreen") + 
  theme_grey(base_size = 14) + 
  labs(title = "Median household income", 
       ___ = "Counties in Maine", 
       x = "ACS estimate (bars represent margins of error)", 
       y = "") + 
  scale_x_continuous(labels = scales::dollar)
Edit and Run Code