You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Shapefile多边形与CSV数据关联并实现价格梯度可视化?

问题描述

我从公开数据源下载了英格兰郡1991年的多边形Shapefile(england_ct_1991.shp)和CSV文件(england_ct_1991.csv),并为CSV新增了唯一对应各郡的price列。通过郡名关联两者后,无法在地图上呈现基于price的颜色梯度效果。以下是我的R代码,使用了ggplot2、sf和tidyverse包:

library(ggplot2)
library(sf)
library(tidyverse)

# map of england counties
map7 <- read_sf("england_ct_1991.shp")
head(map7)

ggplot(map7) +
geom_sf()

# get x (longitude) y (latitude) county names and prices
totalPrices <- read_csv("england_ct_1991.csv")
head(totalPrices)

# join map and csv data on county name
mappedData <- left_join(map7, totalCounts, by="name")
head(mappedData)

# print map
map1 <- ggplot(mappedData, aes( x=x, y=y, group=name)) +
   geom_polygon(aes(fill=price), color="black") +
   geom_sf()

map1
错误点及修正方案
  • 变量名拼写错误:left_join里误用了未定义的totalCounts,实际CSV读取后的变量是totalPrices,这会导致关联失败,price列根本没合并到空间数据中。
  • 图层冲突:同时使用geom_polygon和geom_sf会造成渲染冲突,sf类型的空间数据不需要手动指定坐标和分组,geom_sf可以直接识别并渲染多边形,同时支持填充映射。
  • 无效的坐标映射:sf数据在ggplot中无需手动设置aes(x=x, y=y, group=name),geom_sf会自动处理空间属性。

修正后的代码:

library(ggplot2)
library(sf)
library(tidyverse)

# 读取英格兰郡空间数据
map7 <- read_sf("england_ct_1991.shp")

# 读取包含价格的CSV数据
totalPrices <- read_csv("england_ct_1991.csv")

# 修正变量名,执行数据关联
mappedData <- left_join(map7, totalPrices, by = "name")

# 绘制带价格梯度的地图
map1 <- ggplot(mappedData) +
  geom_sf(aes(fill = price), color = "black") +
  scale_fill_viridis_c(option = "plasma") # 可选:添加美观的渐变颜色标尺,提升可读性

map1

内容的提问来源于stack exchange,提问作者ithoughtso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 04:16:15