Home > Back-end >  ggplot how to plot pie charts on USA map with state's id
ggplot how to plot pie charts on USA map with state's id

Time:06-06

I would like to plot pie charts of different fuel type for each state on USA map. my data includes fuel types and their amount and each state id. I want to know how to plot pie on map for each state with state id?

Thanks,

data <- data.frame(region= c(AL, AR, AZ, CA, IA), 
                  gas= c(25, 45, 45, 60, 75),
                  coal= c(45, 50, 45, 20, 15), 
                  wind= c(30, 5, 10, 20, 10), 
                  solar= c(10, 10, 10, 10, 10))

CodePudding user response:

Using the usmap and the scatterpie packages this could be achieved via ggplot2 like so:

  1. Add coordinates for the pies to your data. In the code below I use the coordinates of the state centers provided by usmapdata::centroid_labels
  2. Add the pies from your data via geom_scatterpie
library(usmap)
library(ggplot2)
library(scatterpie)

states <- us_map("states")

centroids <- usmapdata::centroid_labels("states")[c("x", "y", "abbr")]

data <- merge(data, centroids, by.x = "region", by.y = "abbr", all.x = TRUE)

plot_usmap(regions = "states")  
  geom_scatterpie(aes(x, y, group = region),
    data = data, cols = c("gas", "coal", "wind", "solar")
  )  
  geom_text(aes(x, y, label = region),
            data = data, vjust = 1, nudge_y = -100000
  )

EDIT If you want to exclude some states (or include only some states) you could do so via the exclude or include argument of plot_usmap:

plot_usmap(regions = "states", exclude = c("AK", "HI"))  
  geom_scatterpie(aes(x, y, group = region),
                  data = data, cols = c("gas", "coal", "wind", "solar")
  )  
  geom_text(aes(x, y, label = region),
            data = data, vjust = 1, nudge_y = -100000
  )

  • Related