rggplot2usmap

us states plot in R with election results


I have plotted a figure of the US states in R.

Here is the very simple code:

library(usmap) 
library(ggplot2)
plot_usmap(region = 'states')

And here is the resulting figure: Figure of US states in R - states are not colored

Furthermore, I have a csv file containing the names of the states in US, and a color value, equal to red if that state voted for Republicans or blue if the state voted for Democrats. This is the top 5 rows of the CSV file:

State Color
Alabama #E81B23
Alaska #E81B23
Arizona #1405bd
Arkansas #E81B23

How can I fill the states of my figure based on the colors in the CSV file?


Solution

  • To color the regions specified in the plot_usmap() function, you can provide your data via data= and then set the values= argument to the column in your data used for mapping the colors.

    Here's an example with some randomly-generated data. The plot_usmap() is using a dataset that includes the 50 US states + the District of Columbia, so you'll want to make sure they are all in your dataset or you may get some NA labels.

    library(usmap) 
    library(ggplot2)
    
    set.seed(1234)
    
    color_data <- data.frame(
      state = c(state.name, "District of Columbia"),
      the_colors = sample(c("A", "B"), size=51, replace=TRUE)
    )
    
    plot_usmap(
        region = "states",
        data = color_data,
        values = "the_colors",
        color="white"
      ) +
      scale_fill_manual(values=c("#E81B23", "#1405bd"))
    

    enter image description here

    Note that I think the lines between the states look good in white, so color="white" fixes that. You may also notice that you typically don't specify the actual color in the dataframe - you can specify that via scale_fill_manual(values=...). In your case, you can use scale_fill_identity().

    For your data, just make sure the "States" column in your dataset is renamed "state" and it should work.