R上shapefile映射上散点图的绘图点

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

[朋友,我用下面的代码创建了一个散点图。但是,我希望将散点图上绘制的点显示在shapefile的地图上。有可能的?下面是分散代码示例。

library(readxl)
library(rdist)
library(ggplot2)
library(geosphere)
library(tidyverse)

df<-structure(list(Properties = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19), Latitude = c(-23.8, -23.8, -23.9, -23.9, -23.9,  -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, -23.9, 
                                    + -23.9, -23.9, -23.9, -23.9, -23.9), Longitude = c(-49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.6, -49.7, 
                                    + -49.7, -49.7, -49.7, -49.7, -49.6, -49.6, -49.6, -49.6), Waste = c(526, 350, 526, 469, 285, 175, 175, 350, 350, 175, 350, 175, 175, 364, 
                                    + 175, 175, 350, 45.5, 54.6)), class = "data.frame", row.names = c(NA, -19L))

#cluster
coordinates<-df[c("Latitude","Longitude")]
d<-as.dist(distm(coordinates[,2:1]))
fit.average<-hclust(d,method="average") 

#Number of clusters
clusters<-cutree(fit.average, 2) 
nclusters<-matrix(table(clusters))  
df$cluster <- clusters 

#Localization
center_mass<-matrix(nrow=2,ncol=2)
for(i in 1:2){
center_mass[i,]<-c(weighted.mean(subset(df,cluster==i)$Latitude,subset(df,cluster==i)$Waste),
weighted.mean(subset(df,cluster==i)$Longitude,subset(df,cluster==i)$Waste))}
coordinates$cluster<-clusters 
center_mass<-cbind(center_mass,matrix(c(1:2),ncol=1)) 


#Scatter Plot
suppressPackageStartupMessages(library(ggplot2))
df1<-as.data.frame(center_mass)
colnames(df1) <-c("Latitude", "Longitude", "cluster")
g<-ggplot(data=df,  aes(x=Longitude, y=Latitude,  color=factor(clusters))) + geom_point(aes(x=Longitude, y=Latitude), size = 4)
Centro_View<- g +  geom_text(data=df, mapping=aes(x=eval(Longitude), y=eval(Latitude), label=Waste), size=3, hjust=-0.1)+ geom_point(data=df1, mapping=aes(Longitude, Latitude), color= "green", size=4) + geom_text(data=df1, mapping = aes(x=Longitude, y=Latitude, label = 1:2), color = "black", size = 4)
plot1<-print(Centro_View + ggtitle("Scatter Plot") + theme(plot.title = element_text(hjust = 0.5)))


散射图

enter image description here

enter image description here非常感谢您的朋友!

r scatter-plot shapefile
1个回答
0
投票

您应该能够使用rgdal包读取shapefile,然后使用ggplot2绘制它:https://www.r-graph-gallery.com/168-load-a-shape-file-into-r.html

我认为类似的方法应该起作用:

library(rgdal)
library(broom)
library(ggplot2)

# Read shape file with the rgdal library
my_spdf <- readOGR( 
  dsn = "./folder_w_shapefile",
  layer = "your_shapefile" # Do not need ".shp" file extension
)

# 'Fortify' the data to get a dataframe format required by ggplot2
spdf_fortified <- tidy(my_spdf)

# Plot it
ggplot() +
  geom_polygon(data = spdf_fortified, aes(x = long, y = lat, group = group),
  fill = "#69b3a2", color = "white") +
  geom_point(data = df, aes(x = Longitude, y = Latitude, color = factor(clusters)),
  size = 4) +
  theme_void()
© www.soinside.com 2019 - 2024. All rights reserved.