IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Interactive Data Visualization with plotly in R

Visualizza il corso

Istruzioni dell'esercizio

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

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

# 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()
Modifica ed esegui il codice