使用geom_point绘制R中的人口密度图

时间:2015-09-17 03:32:42

标签: r plot ggplot2

我正在研究加拿大的简单人口密度情节。我有基于邮政编码和纬度/经度here

的人口数据

随着点密度的增加,我希望改进图表以显示颜色变化。这是我的代码:

library(maptools)
library(gdata)
library(RColorBrewer)
library(classInt)
library(maps)
library(ggplot2)
library(ggmap)

Canada <- get_map(location="Canada", zoom=3, maptype="terrain")

ggmap(Canada, extent="normal") + geom_point(data=PopDensity, aes(x=LONG,y=LAT,size=POPULATION), 
alpha = 0.3)+scale_size_continuous(range=c(1,6))

产生类似

的图

so.

我真正喜欢的是一种保持数据点大小相同的方法,但不是将点透明,而是将颜色更改为点密度的函数。

1 个答案:

答案 0 :(得分:4)

您必须先计算密度,然后将值分配给点,以便映射该美学:

library(ggplot2)
library(ggthemes)
library(scales)
library(ggmap)
library(MASS)
library(sp)
library(viridis)

pop <- read.csv("~/Dropbox/PopulationDensity.csv", header=TRUE, stringsAsFactors=FALSE)

# get density polygons
dens <- contourLines(
    kde2d(pop$LONG, pop$LAT, 
          lims=c(expand_range(range(pop$LONG), add=0.5),
                 expand_range(range(pop$LAT), add=0.5))))

# this will be the color aesthetic mapping
pop$Density <- 0

# density levels go from lowest to highest, so iterate over the
# list of polygons (which are in level order), figure out which
# points are in that polygon and assign the level to them

for (i in 1:length(dens)) {
  tmp <- point.in.polygon(pop$LONG, pop$LAT, dens[[i]]$x, dens[[i]]$y)
  pop$Density[which(tmp==1)] <- dens[[i]]$level
}

Canada <- get_map(location="Canada", zoom=3, maptype="terrain")

gg <- ggmap(Canada, extent="normal")
gg <- gg + geom_point(data=pop, aes(x=LONG, y=LAT, color=Density))
gg <- gg + scale_color_viridis()
gg <- gg + theme_map()
gg <- gg + theme(legend.position="none")
gg

enter image description here