簡體   English   中英

ggplot 如何使用州 ID 在美國 map 上繪制 plot 餅圖

[英]ggplot how to plot pie charts on USA map with state's id

我想為美國 map 上的每個 state 繪制不同燃料類型的 plot 餅圖。我的數據包括燃料類型及其數量以及每個 state id。 我想知道如何在 map 上為每個 state 和 state id 分配 plot 餡餅?

謝謝,

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))

使用usmapscatterpie包,這可以通過ggplot2實現,如下所示:

  1. 將餅圖的坐標添加到您的數據中。 在下面的代碼中,我使用了usmapdata::centroid_labels提供的 state 中心的坐標
  2. 通過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
  )

編輯如果您想排除某些狀態(或僅包括某些狀態),您可以通過plot_usmapexcludeinclude參數來實現:

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
  )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM