我想在美国地图上为每个州绘制不同燃料类型的饼图。 我的数据包括燃料类型及其数量以及每个州的 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))
更新
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
来实现,如下所示:
usmapdata::centroid_labels
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
)
编辑 如果您想排除某些状态(或仅包含某些状态),您可以通过
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
)