问题描述
我使用的是 R 编程语言。我正在尝试复制以下 stackoverflow 帖子(创建地理空间热图),但使用开源地图(德克萨斯州奥斯汀)而不是付费版本:Generating spatial heat map via ggmap in R based on a value
在这里使用这个网站,我学会了如何获得开源:https://www.reddit.com/r/Rlanguage/comments/jfnvxn/free_alternatives_for_ggmap/g9m1r4d/
本教程中使用的数据可以从 dropBox 下载(不是我的,这是以前的用户提供的):https://www.dropbox.com/s/0s05cl34bko7ggm/sample_data.csv?dl=0。
从 dropBox 下载并导入 R 后,数据如下所示:
> data = read.csv("sample_data.csv")
> head(data)
average_rate_per_night latitude longitude
1 $82 30.30952 -97.73171
2 $110 30.24430 -97.77447
3 $119 30.30038 -97.77886
4 $105 30.27752 -97.71919
5 $50 30.23294 -97.58938
6 $130 30.23039 -97.76581
library(ggmap)
library(data.table)
map <- get_stamenmap(bBox = c(-97.889302,30.135824,-97.572841,30.450647))
data <- setDT(read.csv(file.choose(),stringsAsFactors = FALSE))
# convert the rate from string into numbers
data[,average_rate_per_night := as.numeric(gsub(",","",substr(average_rate_per_night,2,nchar(average_rate_per_night))))]
# generate bins for the x,y coordinates
xbreaks <- seq(floor(min(data$latitude)),ceiling(max(data$latitude)),by = 0.01)
ybreaks <- seq(floor(min(data$longitude)),ceiling(max(data$longitude)),by = 0.01)
# allocate the data points into the bins
data$latbin <- xbreaks[cut(data$latitude,breaks = xbreaks,labels=F)]
data$longbin <- ybreaks[cut(data$longitude,breaks = ybreaks,labels=F)]
# Summarise the data for each bin
datamat <- data[,list(average_rate_per_night = mean(average_rate_per_night)),by = c("latbin","longbin")]
# 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,"longbin"),all.x = TRUE,all.y = FALSE)
# Fill up the empty bins 0 to smooth the contour plot
datamat[is.na(average_rate_per_night),]$average_rate_per_night <- 0
# Plot the contours
ggmap(map,extent = "device") +
stat_contour(data = datamat,aes(x = longbin,y = latbin,z = average_rate_per_night,fill = ..level..,alpha = ..level..),geom = 'polygon',binwidth = 100) +
scale_fill_gradient(name = "Price",low = "green",high = "red") +
guides(alpha = FALSE)
唯一的问题是,与原始 stackoverflow 帖子中的地图相比,由上述代码生成的地图被“大幅放大”:
map <- get_stamenmap(bBox = c(-95.889302,28.135824,30.450647))
但这导致了以下错误:
Error in grid.Call.graphics(C_raster,x$raster,x$x,x$y,x$width,x$height,:
Empty raster
有人知道如何解决这个问题吗?
谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)