我尝试根据值生成热图 . 这是我的数据集,它由三个变量组成:Lat(纬度),Lon(经度)和Value . https://www.dropbox.com/s/s53xeplywz9jh15/sample_data.csv?dl=0
我查看了相关帖子,发现这很有用:Generating spatial heat map via ggmap in R based on a value
我在那篇帖子中复制了代码,这里我的代码如下:
# import data and libaries
library(ggplot2)
library(ggmap)
Yunan<-read.csv("C:\\Program Files\\RStudio\\data\\pb_sp\\sample_data.csv", header = TRUE)
# call the map to see point distribution
Yunan_map<-get_map(location="yunan",zoom=6,maptype="terrain",scale=2)
ggmap(Yunan_map)+geom_point(data=Yunan,aes(x=Yunan$Lon,y=Yunan$Lat,fill="red",alpha=0.3,size=0.05,shape=21))+scale_shape_identity()
# 1. generate bins for x, y coordinates (unit=decimal degree)
xbreaks <- seq(floor(min(Yunan$Lat,na.rm=TRUE)), ceiling(max(Yunan$Lat,na.rm=TRUE)), by = 0.5)
ybreaks <- seq(floor(min(Yunan$Lon,na.rm=TRUE)), ceiling(max(Yunan$Lon,na.rm=TRUE)), by = 0.5)
# 2. allocate the data points into the bins
Yunan$latbin <- xbreaks[cut(Yunan$Lat, breaks = xbreaks, labels=F)]
Yunan$longbin <- ybreaks[cut(Yunan$Lon, breaks = ybreaks, labels=F)]
# 3. summarise the data for each bin (use the median)
datamat <- Yunan[, list(Value= median(Value)),
by = c("latbin", "longbin" )]
# 4. Merge the summarised data with all possible x, y coordinate combinations to get
# a value for every bin
datamat <- merge(setDT(expand.grid(latbin = xbreaks, longbin = ybreaks)), datamat,
by = c("latbin", "longbin"), all.x = TRUE, all.y = FALSE)
# 5. Fill up the empty bins 0 to smooth the contour plot
datamat[is.na(Value), ]$Value <- 0
# 6. Plot the contours
ggmap(Yunan_map,extent ="device") +
stat_contour(data = datamat, aes(x = longbin, y = latbin, z = Value,
fill = ..level.., alpha = ..level..), geom = 'polygon', binwidth = 30) +
scale_fill_gradient(name = "Value", low = "green", high = "red") +
guides(alpha = FALSE)
但是,我遇到了两个问题
- 执行完第3步(汇总每个bin的数据)后,收到以下错误信息:
[.data.frame
中的错误( Cloud 南,,列表(值=中位数(值)),= c("latbin",:未使用的参数(by = c("latbin","longbin"))
- 我希望将颜色方案从渐变颜色更改为离散颜色,如下图所示:
由于我的数据集中的值范围从17到21,我想将它们分类到不同的区域,例如17-17.5,17.5-18,18-18.5 ....以及相应的颜色 .
我可以解决这些问题的任何建议 . 提前致谢 .