CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

Interactive Data Visualization with plotly in R

Afficher le cours

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.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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()
Modifier et exécuter le code