gpt4 book ai didi

r - 如何使用变量填充ggplot shapefile map ?

转载 作者:行者123 更新时间:2023-12-04 11:53:17 25 4
gpt4 key购买 nike

我正在尝试填写一张美国 map ,其中每个州都按平均工资(默认色标)填写。我有 shapefile 和一个看起来像这样的数据框(数据伪造):

data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")

这是我的代码:

library(tidyverse)
library(rgdal)

map <- readOGR(dsn = ".", layer = "usamap")

PlotData <- merge(map, data, by = "State")

到目前为止一切正常。我也可以制作一张空 map :

map_base <- ggplot(data = PlotData, mapping=(aes(x=long, y = lat, group = group)) +
geom_polygon(color = "black", fill = NA)
map_base

但是,我无法用值填充 map 。

map_base <- ggplot(data = PlotData, mapping=(aes(x=long, y = lat, group = group)) +
geom_polygon(color = "black", fill = PlotData$MeanSalary)
map_base

我收到这个错误:

Error: Aesthetics must be either length 1 or the same as the data (2834334): fill

我哪里错了?

最佳答案

我在这里提供了两种使用 ggplot2 绘制多边形的解决方案。

方案一:geom_sf

sf 类是R 中的下一代空间数据类。geom_sf 可以绘制sf 对象。为此,我们需要将 sp 对象转换为 sf 对象。在这里,我使用了 USAboundaries 包中的状态空间多边形作为示例。

library(tidyverse)
library(sf)
library(USAboundaries)

# Get the state data
state <- us_states()

# Check the class
class(state)
# [1] "sf" "data.frame"

# Create example data frame
data <- structure(list(State = c("Arkansas",
"Iowa",
"California",
"Idaho"),
MeanSalary = c(50000,60000,62000,55000)),
row.names=1:4, class = "data.frame")

# Merge data to state and filter for these records
state_filter <- state %>%
left_join(data, by = c("name" = "State")) %>%
# Remove Hawaii, Alaska, and Puerto Rico to just focus on the rest states
filter(!name %in% c("Hawaii", "Alaska", "Puerto Rico"))

# Plot the data
ggplot(state_filter) +
geom_sf(aes(fill = MeanSalary))

enter image description here

方案二:ggspatial包

ggspatial 包 可以绘制sp 对象。因此,如果您不想使用 sf 对象,可以选择使用 ggspatial

library(tidyverse)
library(sf)
library(USAboundaries)
library(sp)
library(ggspatial)

# Convert the sf object to sp object
state_filter_sp <- as(state_filter, "Spatial")

# Plot the data
ggplot() +
annotation_spatial(state_filter_sp) +
layer_spatial(state_filter_sp, aes(fill = MeanSalary))

enter image description here

关于r - 如何使用变量填充ggplot shapefile map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55071999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com