r - 使用 ggplot2 从 KML 数据绘制等值线图

标签 r ggplot2 kml

如何使用来自 KML 数据源的 ggplot2 绘制等值线图或专题图?

示例 KML:https://dl.dropbox.com/u/1156404/nhs_pct.kml

示例数据:https://dl.dropbox.com/u/1156404/nhs_dent_stat_pct.csv

这是我到目前为止所得到的:

install.packages("rgdal")
library(rgdal)
library(ggplot2)

fn='nhs_pct.kml'

#Look up the list of layers
ogrListLayers(fn)

#The KML file was originally grabbed from Google Fusion Tables
#There's only one layer...but we still need to identify it
kml=readOGR(fn,layer='Fusiontables folder')

#This seems to work for plotting boundaries:
plot(kml)

#And this:
kk=fortify(kml)
ggplot(kk, aes(x=long, y=lat,group=group))+ geom_polygon()

#Add some data into the mix
nhs <- read.csv("nhs_dent_stat_pct.csv")

kml@data=merge(kml@data,nhs,by.x='Name',by.y='PCT.ONS.CODE')

#I think I can plot against this data using plot()?
plot(kml,col=gray(kml@data$A.30.Sep.2012/100))
#But is that actually doing what I think it's doing?!
#And if so, how can experiment using other colour palettes?

#But the real question is: HOW DO I DO COLOUR PLOTS USING gggplot?
ggplot(kk, aes(x=long, y=lat,group=group)) #+ ????

所以我的问题是:如何使用例如 kml@data$A.30.Sep.2012 值来为区域着色?

作为补充问题:我如何再次在 ggplot 上下文中尝试不同的调色板?

最佳答案

在 R 中绘制 map 通常很痛苦。这是一个很大程度上遵循 Hadley 在 https://github.com/hadley/ggplot2/wiki/plotting-polygon-shapefiles 上的教程的答案。

library(maptools)
library(rgdal)
library(ggplot2)
library(plyr)

fn='nhs_pct.kml'
nhs <- read.csv("nhs_dent_stat_pct.csv")

kml <- readOGR(fn, layer="Fusiontables folder")

注意:我收到一条关于孤儿洞的消息。阅读 https://stat.ethz.ch/pipermail/r-help/2011-July/283281.html 后,我加入了以下行

slot(kml, "polygons") <- lapply(slot(kml, "polygons"), checkPolygonsHoles)

## The rest more or less follows Hadley's tutorial 
kml.points = fortify(kml, region="Name")
kml.df = merge(kml.points, kml@data, by.x="id",by.y="Name",sort=FALSE)
kml.df <- merge(kml.df,nhs,by.x="id",by.y="PCT.ONS.CODE",sort=FALSE,all.x=T,all.y=F)

## Order matters for geom_path!
kml.df <- kml.df[order(kml.df$order),]

nhs.plot <- ggplot(kml.df, aes(long,lat,group=group,fill=A.30.Sep.2012)) + 
  geom_polygon() +
  geom_path(color="gray") +
  coord_equal() +
  scale_fill_gradient("The outcome") + 
    scale_x_continuous("") + scale_y_continuous("") +   theme_bw()

关于r - 使用 ggplot2 从 KML 数据绘制等值线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13762793/

相关文章:

r - grid.arrange() : arrange 3 plots neatly

javascript - Google Maps API 和 KML 文件 LocalHost 开发选项

python - 将 Pandas 数据帧读入 R

r - 为要在数据表的搜索栏中使用的特定值指定不同的名称

r - 将模拟泊松分布添加到 ggplot

r - 面标签字体大小

kml - 如何将图例添加到我的 KML 以使其不移动

android - 在自定义图 block 上使用 Google map KML 导入实用程序

r - 使用 R 计算每列缺失值的百分比

r - Knit:不要取一大块金银丝