如何将 shapefile 多边形映射到 CSV 数据

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

我从此处下载的 zip 文件下载了一个多边形文件 (england_ct_1991.shp) ,并从此处下载了 CSV 文件 (england_ct_1991.csv) ,我想将其连接在一起(所有公共数据)。我在 CSV 文件中添加了一个名为“价格”的新列,因此每个县都有一个独特的价格,如下所示:

name,label,x,y,price
Avon,9,360567.1834,171823.554,11
Avon,9,322865.922,160665.4829,11
Bedfordshire,10,506219.5005,242767.306,20
Berkshire,11,464403.02,172809.5331,23....

我以县名加入了 shp 和 CSV。问题是地图没有叠加在价格上以根据价格在县上显示漂亮的颜色渐变。我检查了一些 YouTube 教程,说明重要的部分是加入,但它对他们有用,所以我不确定我做错了什么?

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

更新: 我正在尝试使用这些来源添加标签到组这样文本就不会冲突。我将此块添加到 John Granger 的代码中,但某些标签未出现,而其他标签则重复。有没有办法来解决这个问题?我尝试减轻渐变,以防它覆盖文本。

cnames2 <- aggregate(cbind(x, y, price) ~ name, data=totalPrices, 
                 FUN=function(x)mean(range(x)))
head(cnames2)

library(ggrepel)

map7 %>%
  left_join(cnames2) %>%
  ggplot() +
  geom_sf(aes(fill = price),color="black")+
  theme(axis.text = element_blank(), 
    axis.ticks = element_blank(),
    panel.background = element_blank()) +
  geom_text_repel(aes(label = name, geometry = geometry), 
      stat = "sf_coordinates", size=3) +
  scale_fill_gradient(low = "white", high = "darkgrey", 
              na.value = 'black', guide = 'colorbar',  
              aesthetics = 'fill')
r csv ggplot2 spatial shapefile
1个回答
0
投票

重点是运行时

Detected an unexpected many-to-many relationship between x and y
的警告
left_join(map7, totalCounts, by="name")

因此请保持您的

totalPrices
数据是唯一的,即
name
列中没有重复的区域。

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

map7 <- read_sf("england_ct_1991.shp")

totalPrices <- read_csv("england_ct_1991.csv")

new <- totalPrices %>%
  group_by(name) %>%
  mutate(price = rnorm(1)) %>% 
  distinct(name, price)
new

## A tibble: 47 × 2
## Groups:   name [47]
#   name                           price
#   <chr>                          <dbl>
# 1 Lincolnshire                 -2.45  
# 2 Cumbria                      -0.413 
# 3 North Yorkshire               0.566 
# 4 Northumberland                0.179 
# 5 Cornwall and Isles of Scilly  1.05  
# 6 Devon                        -0.493 
# 7 Somerset                      0.324 
# 8 Dorset                        0.704 
# 9 East Sussex                   1.32  
#10 Wiltshire                     0.0161
## ℹ 37 more rows
## ℹ Use `print(n = ...)` to see more rows


map7 %>%
  left_join(new) %>%
  ggplot() +
  geom_sf(aes(fill = price),color="black")
© www.soinside.com 2019 - 2024. All rights reserved.