首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在R中绘制plot_usmap包的问题

在R中绘制plot_usmap包的问题
EN

Stack Overflow用户
提问于 2022-06-18 05:02:22
回答 1查看 120关注 0票数 0

我想在美国地图上绘制我的数据,我使用了plot_usmap软件包,但它不起作用。这是我的数据:

代码语言:javascript
复制
dt<- data.frame(fips = c("CA", "AL", "NY","IA", "TX","CA", "AL", "NY","IA", "TX"),
                 value = c(25, 45, 45, 60, 75,15, 65, 75, 20, 65),
                  year=c(2000, 2000, 2000, 2000, 2000,2010, 2010, 2010, 2010, 2010))

这是我的密码:

代码语言:javascript
复制
plot_usmap(data = dt, values = "value", exclude = c("AK", "HI"))+
   scale_fill_continuous(low = "white", high = "red", name = "Ele gen (EJ)", label = scales::comma)+ facet_grid("year")

这是最后的地图:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-18 10:43:28

虽然plot_usmap使绘制快速地图变得很容易,但我认为,在您的示例中,使用ggplot2从头构建映射是可行的。

为此,您可以首先通过us_map获取原始地图数据,并将数据与地图数据合并。

但是,由于您的数据包含多年,但只有一些状态,所以我们必须“完成”数据集才能包含每一对年份和状态的观测结果。否则,按年计较是行不通的。为此,我首先按年份划分数据,将单个年份数据合并到地图数据,使用tidyr::fill填充年份列,最后按行绑定数据集:

代码语言:javascript
复制
dt <- data.frame(fips = c("CA", "AL", "NY","IA", "TX","CA", "AL", "NY","IA", "TX"),
                value = c(25, 45, 45, 60, 75,15, 65, 75, 20, 65),
                year=c(2000, 2000, 2000, 2000, 2000,2010, 2010, 2010, 2010, 2010))

library(usmap)
library(ggplot2)
library(dplyr)

# Map data
states <- us_map(exclude = c("AK", "HI"))

# Split, join, bind
states_data <- split(dt, dt$year) |> 
  lapply(function(x) left_join(states, x, by = c("abbr" = "fips"))) |> 
  lapply(function(x) tidyr::fill(x, year, .direction = "downup")) |> 
  bind_rows() |> 
  arrange(year, group, order)

ggplot(states_data, aes(x, y, fill = value, group = group)) +
  geom_polygon() +
  scale_fill_continuous(low = "white", high = "red", name = "Ele gen (EJ)", label = scales::comma) +
  facet_grid(~year) +
  coord_equal() +
  ggthemes::theme_map() +
  theme(legend.position = "bottom")

用所有状态的数据编辑真实数据的--数据准备要容易得多:

代码语言:javascript
复制
# Join and arrange
states_data <- left_join(states, dt, by = c("abbr" = "fips")) |> 
  arrange(emission, growth, group, order)

ggplot(states_data, aes(x, y, fill = value, group = group)) +
  geom_polygon() +
  scale_fill_continuous(low = "white", high = "red", name = "Ele gen (EJ)", label = scales::comma) +
  facet_grid(emission~growth) +
  coord_equal() +
  ggthemes::theme_map() +
  theme(legend.position = "bottom")

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72666796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档