Get startedGet started for free

Mapping Senate winners

There were 33 Senate seats on the ballot in the 2018 midterms (plus two special elections that we'll ignore in this exercise). Your task is to create a choropleth map using the winning candidate's political party to color in the state.

This task requires you to map a factor to the fill color. However, the z aesthetic expects a numeric variable. An easy work around is to convert party to a numeric variable via as.numeric(party) and then manually specify the desired colors in add_trace(). Additionally, the colorbar is no longer very useful, and can be removed by adding the layer hide_colorbar().

The senate_winners data frame and plotly have already been loaded for you.

This exercise is part of the course

Interactive Data Visualization with plotly in R

View Course

Exercise instructions

  • Create a choropleth map of the where the color of the state represents the winning party.
  • In add_trace(), manually specify the colors "dodgerblue", "mediumseagreen", and "tomato" (in that order).
  • Complete the hover info text with the appropriate column names.

Hands-on interactive exercise

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

# Create a choropleth map displaying the Senate results
senate_winners %>%
  plot_geo(locationmode = ___) %>%
  add_trace(___, ___,
    ___ = ___(___, ___, ___),
    hoverinfo = "text",
    text = ~paste("Candidate:", ___, "
", "Party:", ___, "
", "% vote:", round(___, 1)) ) %>% layout(geo = list(scope = 'usa')) %>% hide_colorbar()
Edit and Run Code