C J
C J

Reputation: 3

Plotting the Frequency of Observations in States in R

I would like to plot the frequency of observations in our data seen in each state.

Here is the data:

structure(list(fips = c("02", "04", "05", "06", "08", "13", "17", 
"18", "19", "20", "23", "24", "26", "27", "31", "34", "36", "37", 
"39", "41", "42", "47", "48", "49", "51", "55"), Freq = c(1L, 
3L, 1L, 3L, 2L, 1L, 4L, 9L, 3L, 1L, 1L, 1L, 36L, 2L, 1L, 1L, 
4L, 4L, 7L, 1L, 10L, 1L, 2L, 1L, 1L, 7L), statenames = c("Alaska", 
"Arizona", "Arkansas", "California", "Colorado", "Georgia", "Illinois", 
"Indiana", "Iowa", "Kansas", "Maine", "Maryland", "Michigan", 
"Minnesota", "Nebraska", "New Jersey", "New York", "North Carolina", 
"Ohio", "Oregon", "Pennsylvania", "Tennessee", "Texas", "Utah", 
"Virginia", "Wisconsin"), state.abb = c("AK", "AZ", "AR", "CA", 
"CO", "GA", "IL", "IN", "IA", "KS", "ME", "MD", "MI", "MN", "NE", 
"NJ", "NY", "NC", "OH", "OR", "PA", "TN", "TX", "UT", "VA", "WI"
), states = c("alaska", "arizona", "arkansas", "california", 
"colorado", "georgia", "illinois", "indiana", "iowa", "kansas", 
"maine", "maryland", "michigan", "minnesota", "nebraska", "new jersey", 
"new york", "north carolina", "ohio", "oregon", "pennsylvania", 
"tennessee", "texas", "utah", "virginia", "wisconsin")), row.names = c(2L, 
3L, 4L, 5L, 6L, 11L, 14L, 15L, 16L, 17L, 20L, 21L, 23L, 24L, 
28L, 31L, 33L, 34L, 36L, 38L, 39L, 43L, 44L, 45L, 47L, 50L), class = "data.frame")

I'm running this code:

library(maps)
library(maptools)
library(sp)

mapUSA <- map('state',  fill = TRUE,  plot = FALSE)
nms <- sapply(strsplit(mapUSA$names,  ':'),  function(x)x[1])
USApolygons <- map2SpatialPolygons(mapUSA,  IDs = nms,  CRS('+proj=longlat'))

idx <- match(unique(nms),  small_df$states)
dat2 <- data.frame(value = idx, state = unique(nms))
row.names(dat2) <- unique(nms)
USAsp <- SpatialPolygonsDataFrame(USApolygons,  data = dat2)

spplot(USAsp['value'])

However, the resulting image is incorrect:

enter image description here

I would like the color bar to represent the frequency of each state observed in our data in the "Freq" column

I've tried various packages, and this was the one I came closest to getting what I wanted. I'm open to trying easier packages out there if they exist!

Upvotes: 0

Views: 110

Answers (1)

Ben
Ben

Reputation: 30474

To plot Freq column in small_df data, you can merge your states with your small_df. This just requires minor modifications to what you have, and then you can plot the Freq column.

dat2 <- data.frame(state = unique(nms))
dat2 <- merge(dat2, small_df, by.x = "state", by.y = "states", all.x = TRUE)
row.names(dat2) <- dat2$state
USAsp <- SpatialPolygonsDataFrame(USApolygons,  data = dat2)

spplot(USAsp['Freq'])

Map

map of states including Freq column of data

Upvotes: 0

Related Questions