我从此处下载的 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
重点是运行时
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")