ggplot 如何在美国地图上绘制带有州 ID 的饼图

问题描述 投票:0回答:1

我想在美国地图上为每个州绘制不同燃料类型的饼图。 我的数据包括燃料类型及其数量以及每个州的 ID。我想知道如何在地图上为每个具有州 ID 的州绘制饼图?

谢谢,

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))
r ggplot2 scatterpie
1个回答
2
投票

更新

usmap
已在版本
0.7.0
中进行了现代化改造,现在将数据作为简单功能返回。因此,获取散点饼的坐标需要稍微多一些努力才能从 sf 对象检索坐标:

library(usmap)
library(ggplot2)
library(scatterpie)

states <- us_map("states")

centroids <- usmapdata::centroid_labels("states")

centroids <- cbind(
  abbr = centroids$abbr,
  sf::st_coordinates(centroids)
) |>
  as.data.frame() |>
  transform(
    X = as.numeric(X),
    Y = as.numeric(Y)
  )

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

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

原答案

使用

usmap
scatterpie
包,这可以通过
ggplot2
来实现,如下所示:

  1. 将饼图的坐标添加到您的数据中。在下面的代码中,我使用
    usmapdata::centroid_labels
  2. 提供的州中心坐标
  3. 通过
    geom_scatterpie
  4. 添加数据中的饼图
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
  )

编辑 如果您想排除某些状态(或仅包含某些状态),您可以通过

exclude
include
参数来实现:
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 )

© www.soinside.com 2019 - 2024. All rights reserved.