首先,让我们加载数据:
data<-read.csv(file = "NY subsample.csv")
数据点
然后,让我们尝试绘制数据的基本位置和值:
require('ggplot2')
# start with points
pred.points <- ggplot(data = data,
aes(x = GEO_CENTROID_LON,
y = GEO_CENTROID_LAT,
colour = prediction)) +
geom_point()
print(pred.points)
ggsave(filename = "NYSubsamplePredPoints.png",
plot = p2,
scale = 1,
width = 5, height = 3,
dpi = 300)
这给了我们这个:
分箱数据
然后,您可以尝试使用以下方法绘制二维区域中的平均值stat_summary2d()
:
pred.stat <- ggplot(data = data,
aes(x = GEO_CENTROID_LON,
y = GEO_CENTROID_LAT,
z = prediction)) +
stat_summary2d(fun = mean)
print(pred.stat)
ggsave(filename = "NYSubsamplePredStat.png",
plot = pred.stat,
scale = 1,
width = 5, height = 3,
dpi = 300)
这为我们提供了每个框中预测的平均值的图。
装箱并使用自定义颜色图和正确的投影
接下来,我们可以设置 bin 大小、色阶和固定投影:
# refine breaks and palette ----
require('RColorBrewer')
YlOrBr <- c("#FFFFD4", "#FED98E", "#FE9929", "#D95F0E", "#993404")
pred.stat.bin.width <- ggplot(data = data,
aes(x = GEO_CENTROID_LON,
y = GEO_CENTROID_LAT,
z = prediction)) +
stat_summary2d(fun = median, binwidth = c(.05, .05)) +
scale_fill_gradientn(name = "Median",
colours = YlOrBr,
space = "Lab") +
coord_map()
print(pred.stat.bin.width)
ggsave(filename = "NYSubsamplePredStatBinWidth.png",
plot = pred.stat.bin.width,
scale = 1,
width = 5, height = 3,
dpi = 300)
这给了我们这个:
绘制在基本地图上
最后,这是覆盖在地图上的数据。
require('ggmap')
map.in <- get_map(location = c(min(data$GEO_CENTROID_LON),
min(data$GEO_CENTROID_LAT),
max(data$GEO_CENTROID_LON),
max(data$GEO_CENTROID_LAT)),
source = "osm")
theme_set(theme_bw(base_size = 8))
pred.stat.map <- ggmap(map.in) %+% data +
aes(x = GEO_CENTROID_LON,
y = GEO_CENTROID_LAT,
z = prediction) +
stat_summary2d(fun = median,
binwidth = c(.05, .05),
alpha = 0.5) +
scale_fill_gradientn(name = "Median",
colours = YlOrBr,
space = "Lab") +
labs(x = "Longitude",
y = "Latitude") +
coord_map()
print(pred.stat.map)
ggsave(filename = "NYSubsamplePredStatMap.png",
plot = pred.stat.map,
scale = 1,
width = 5, height = 3,
dpi = 300)
设置颜色图
最后,要将颜色图设置为http://www.cadmaps.com/images/HeatMapImage.jpg之类的东西,我们可以猜测一下颜色图:
colormap <- c("Violet","Blue","Green","Yellow","Red","White")
并再次进行绘图:
pred.stat.map.final <- ggmap(map.in) %+% data +
aes(x = GEO_CENTROID_LON,
y = GEO_CENTROID_LAT,
z = prediction) +
stat_summary2d(fun = median,
binwidth = c(.05, .05),
alpha = 1.0) +
scale_fill_gradientn(name = "Median",
colours = colormap,
space = "Lab") +
labs(x = "Longitude",
y = "Latitude") +
coord_map()
print(pred.stat.map.final)