Spatial Visualization with ggplot2

ggplot2的精髓在于图层叠加,并且它的默认参数可以实现良好的可视化效果。ggmap是基于ggplot2包的图形语法。

  • 散点图
  • ggplot
  • ggmap

散点图

读取数据

1
2
3
library(rgdal)
lnd <- readOGR("data","london_sport")
lnd$Pop_2001 <- as.numeric(as.character(lnd$Pop_2001))

2.读取shapfile数据
3.将因子型数据转换为数值型数据

ggplot底图

底图基本结构:数据名称和X轴、Y轴参数。

1
2
library(ggplot2)
p <- ggplot(lnd@data, aes(Partic_Per, Pop_2001))

**ggplot():第一个参数:数据名称;第二个参数:ggplot():内部的aes()**分别是X轴、y轴参数。

增加图层

1
2
p + geom_point(aes(color = Partic_Per, size = Pop_2001)) +
geom_text(size = 2, aes(label = name))

1.geom_point内部的**aes():**点的颜色大小参数
2.**geom_text:**第一个参数:点的大小;第二个参数点标签的内容

Figure16-ggplot for text

ggmap

ggmapggplot2在空间数据可视化上的应用。ggmap不能直接识别空间数据,需要用fortify()函数将空间数据转换为data.frame格式。

转化data.frame

1
2
library(rgeos)
lnd_f <- fortify(lnd) # maptools/rgeos

1.fortify()位于maptools/rgeos安装包下
2.将空间数据
lnd
转化为了data.frame格式。

查看数据结构

1
2
summary(lnd)
summary(lnd_f)

运行以上代码, 发现经过fortify()函数处理后,lnd_f不再具有lnd的属性数据(ons_label,name,Partic_Per,Pop_2001)
因此需要dplyer中的left_join()函数进行属性连接。

属性连接

1
2
3
4
5
head(lnd_f, n = 2) # peak at the fortified data
lnd$id <- row.names(lnd) # allocate an id variable to the sp data
head(lnd@data, n = 2) # final check before join (requires shared variable name)
lnd_f <- dplyr::left_join(lnd_f, lnd@data) # join the data
summary(lnd_f)

1.查看lnd_f的前两行
2.生成 行名称变量:id
3.查看lnd数据槽的前两行
4.根据id将左边的lnd_f数据与lnd中的属性数据连接
5.查看lnd_f的数据结构

作图

1
2
3
4
5
6
7
map <- ggplot(lnd_f, aes(long, lat, group = group, fill = Partic_Per)) +
geom_polygon() + coord_equal() +
labs(x = "Easting (m)", y = "Northing (m)",
fill = "% Sports\nParticipation") +
ggtitle("London Sports Participation")
map
map + scale_fill_gradient(low = "white", high = "black")

1.lnd_f:data.frame; aes: X轴经度,Y轴纬度,Partic_per必须为data.frame:lnd_f中的变量
2.空间数据作图常用参数:geom_polygon()绘制多边形
3.X轴标题,Y轴标题
4.图例标题
5.图表总标题
6.作图,有默认颜色,如图17所示
7.作图,指定颜色:低为”白色”,高为”黑色”,如图18所示

Figure18-Greyscale map
-------------文章结束啦 ฅ●ω●ฅ 感谢您的阅读-------------