7 等高线,地图,转换为图形文件

等高线图

contour(x=10*1:nrow(volcano), y=10*1:ncol(volcano), z=volcano,#内置数据集
xlab="Metres West",ylab="Metres North", 
main="Topography of Maunga Whau Volcano")#对X,Y*10以后,z仍会自动对应。(试一下不*10的结果

  

优化等高线图
par(las=1)
plot(0,0,xlim=c(0,10*nrow(volcano)),ylim=c(0,10*ncol(volcano)),
type="n",xlab="Metres West",
ylab="Metres North",main="Topography of Maunga Whau Volcano")#不画图,只是一个框架

u<-par("usr")

rect(u[1],u[3],u[2],u[4],col="lightgreen")#颜色

contour(x=10*1:nrow(volcano),y=10*1:ncol(volcano),
volcano,col="red",add=TRUE)#add 加到现有的图上

等高线之间添加颜色
filled.contour(x = 10*1:nrow(volcano),y = 10*1:ncol(volcano),
z = volcano, color.palette = terrain.colors,#选择调色盘,会自动计算所需颜色的数目。也可以指定颜色数,
plot.title = title(main = "The Topography of Maunga Whau",
xlab = "Meters North",ylab = "Meters West"),
               plot.axes = {axis(1, seq(100, 800, by = 100))
                                    axis(2, seq(100, 600, by = 100))},
key.title = title(main="Height\n(meters)"),
key.axes = axis(4, seq(90, 190, by = 10)))#这一画图方法,会画出两幅图,主图(plot)和图例(key),所以需要分别指定title和坐标.所以需要使用plot.title key.title plot.axes key.axes。 在这里,我们不能把axes=False 然后画完图以后再用axis()添加坐标轴。因为这一的话坐标轴会超过主图,涵盖图例。


filled.contour(x = 10*1:nrow(volcano), y = 10*1:ncol(volcano), z = volcano,
color.palette = terrain.colors,
plot.title = title(main = "The Topography of Maunga Whau",
xlab = "Meters North",ylab = "Meters West"),nlevels=100,#确定颜色的数目。会比上图更平滑,默认是20.但这样图例会比较难看
plot.axes = {axis(1, seq(100, 800, by = 100))
axis(2, seq(100, 600, by = 100))},
key.title = title(main="Height\n(meters)"),
key.axes = axis(4, seq(90, 190, by = 10)))

三维地形图#更多内容参见帮助
install.packages("rgl")
library(rgl)

z <- 2 * volcano#3D效果更明显
x <- 10 * (1:nrow(z))
y <- 10 * (1:ncol(z))

zlim <- range(z)
zlen <- zlim[2] - zlim[1] + 1

colorlut <- terrain.colors(zlen)
col <- colorlut[ z-zlim[1]+1 ]#这里,每个z都有自己的颜色。

rgl.open()
rgl.surface(x, y, z, color=col, back="lines")#可见的区域下面是线。

时间序列可视化,在日历热力图

 

source("calendarHeat.R")
stock.data <- read.csv("google.csv")

install.packages("chron")
library("chron")

calendarHeat(dates=stock.data$Date,#date.form的默认格式是YYYY-MM-DD,和我们这个股票数据匹配。如果数据的日期格式不一样,也可以更改。
values=stock.data$Adj.Close,
varname="Google Adjusted Close")

install.packages("openair")#另一种方法,openair本来是用来分析空气污染的
library(openair)

calendarPlot(mydata)#最简单,mydata是内置数据集。

mydata$sales<-rnorm(length(mydata$nox),mean=1000,sd=1500)#向mydata中添加数据

calendarPlot(mydata,pollutant="sales",main="Daily Sales in 2003")#因为这个包本来是为了处理空气污染的,所以这边是把 pollutant改掉。

 

地图
install.packages("maps")#地图包
library(maps)

install.packages("WDI")#世界银行关于各个国家的数据(好像是个可以联网更新的API)
library(WDI)

install.packages("RColorBrewer")#调色盘
library(RColorBrewer)

colors = brewer.pal(7,"PuRd")

wgdp<-WDIsearch("gdp")#会得到一堆与GDP相关的参数

w<-WDI(country="all", indicator=wgdp[4,1], start=2005, end=2005)#选择相应需要的参数

w[63,1] <- "USA"

x<-map(plot=FALSE)

x$measure<-array(NA,dim=length(x$names))#添加一个列,命名为measure

for(i in 1:length(w$country)) {
      for(j in 1:length(x$names)) {
           if(grepl(w$country[i],x$names[j],ignore.case=T))#这边,查找x中的names中是否有w中的country(这边名字的比较并不精确,因为同一个国家在两个数据集的名字可能不同)。忽略大小写差异
                x$measure[j]<-w[i,3]#如果有w中的country和x中的name对应,则赋值。
       }
}

sd <- data.frame(col=colors,
values <- seq(min(x$measure[!is.na(x$measure)]),
max(x$measure[!is.na(x$measure)]) *1.0001,
length.out=7))

sc<-array("#FFFFFF",dim=length(x$names))
          
for (i in 1:length(x$measure))
        if(!is.na(x$measure[i]))
             sc[i]=as.character(sd$col[findInterval(x$measure[i],
             sd$values)])

#2-column layout with color scale to the right of the map

layout(matrix(data=c(2,1), nrow=1, ncol=2), widths=c(8,1),#c(2,1)就是先画2,后画1.
heights=c(8,1))

# Color Scale first
breaks<-sd$values

par(mar = c(20,1,20,7),oma=c(0.2,0.2,0.2,0.2),mex=0.5)

image(x=1, y=0:length(breaks),z=t(matrix(breaks))*1.001,
col=colors[1:length(breaks)-1],axes=FALSE
breaks=breaks,xlab="",ylab="",xaxt="n")

axis(side=4,at=0:(length(breaks)-1),
labels=round(breaks),col="white",las=1)

abline(h=c(1:length(breaks)),col="white",lwd=2,xpd=F)

#Map
map(col=sc,fill=TRUE,lty="blank")

# If you get a figure margins error while running the above code,
enlarge the plot device or adjust the margins so that the graph and
scale fit within the device.

map(add=TRUE,col="gray",fill=FALSE)
title("CO2 emissions (kg per 2000 US$ of GDP)")

 

区域地图
library(maps)

library(RColorBrewer)

x<-map("state",plot=FALSE)#现在x就包含一个state的轮廓图。可以看看x是这样的形式。

for(i in 1:length(rownames(USArrests))) {
      for(j in 1:length(x$names)) {
            if(grepl(rownames(USArrests)[i],x$names[j],ignore.case=T))
                   x$measure[j]<-as.double(USArrests$Murder[i])#向x中添加数据
         }
}

colors <- brewer.pal(7,"Reds")

sd <- data.frame(col=colors,
values=seq(min(x$measure[!is.na(x$measure)]),
max(x$measure[!is.na(x$measure)])*1.0001,
length.out=7))#从小到大,分成7分。

breaks<-sd$values

matchcol<-function(y) {
     as.character(sd$col[findInterval(y,sd$values)])
}

layout(matrix(data=c(2,1), nrow=1, ncol=2),
widths=c(8,1), heights=c(8,1))

# Color Scale first
par(mar = c(20,1,20,7),oma=c(0.2,0.2,0.2,0.2),mex=0.5)

image(x=1, y=0:length(breaks),z=t(matrix(breaks))*1.001,
col=colors[1:length(breaks)-1],axes=FALSE,breaks=breaks,
xlab="", ylab="", xaxt="n")

axis(4,at=0:(length(breaks)-1),
labels=round(breaks),col="white",las=1)

abline(h=c(1:length(breaks)),col="white",lwd=2,xpd=F)

#Map
map("state", boundary = FALSE,col=matchcol(x$measure),#这边就是使得col成为一个变量
fill=TRUE,lty="blank")
map("state", col="white",add = TRUE)
title("Murder Rates by US State in 1973 \n
(arrests per 100,000 residents)", line=2)#两行的形式


map("county", "new york")# draw a county map of New York

map("state", region = c("california", "oregon", "nevada"))#draw a map with three states 

map('italy', fill = TRUE, col = brewer.pal(7,"Set1"))


install.packages("sp")
library(sp)
load(url("http://gadm.org/data/rda/FRA_adm1.RData"))#maps数据包中,只有地图,但没有数据。这个网有很多地理数据

gadm$rainfall<-rnorm(length(gadm$NAME_1),mean=50,sd=15)#假设的降雨量

spplot(gadm,"rainfall", col.regions = rev(terrain.colors(gadm$rainfall)),
main="Rainfall (simulated) in French administrative regions")


把数据画在google地图上
install.packages("rgdal")
library(rgdal)

install.packages("RgoogleMaps")
library(RgoogleMaps)

air<-read.csv("londonair.csv")

london<-GetMap(center=c(51.51,-0.116),#确定地图中心点的经纬度。zoom的数字越大,越详细。
zoom =10, destfile = "London.png",maptype = "mobile")#选择一般的路网图

PlotOnStaticMap(london,lat = air$lat, lon = air$lon,
cex=2,pch=19,col=as.character(air$color))

london<-GetMap(center=c(51.51,-0.116),zoom =13,
destfile = "London_satellite.png",maptype = "satellite")#选择卫星图,有"roadmap", "mobile", "satellite", "terrain", "hybrid", "mapmaker-roadmap", and "mapmaker-hybrid".

PlotOnStaticMap(london,lat = air$lat, lon = air$lon,
cex=2,pch=19,col=as.character(air$color))

 

#前面,add=True可以在原来的图上加图,默认为False。Fun=lines可以划线。fun=function。


GetMap(center=c(40.714728,-73.99867), zoom =14,
destfile = "Manhattan.png", maptype = "hybrid");

GetMap.OSM(lonR= c(-74.67102, -74.63943),#另一个地图来源网址
latR = c(40.33804,40.3556),scale = 7500,
destfile = "PrincetonOSM.png")


KML数据(创建和读取)

install.packages("rgdal")

library(rgdal)

cities <- readOGR(system.file("vectors", package = "rgdal")[1],"cities")

writeOGR(cities, "cities.kml", "cities", driver="KML")

df <- readOGR("cities.kml", "cities")

 

deal with ESRI 

install.packages("maptools")
library(maptools)

sfdata <- readShapeSpatial(system.file("shapes/sids.shp",
package="maptools")[1], proj4string=CRS("+proj=longlat"))

plot(sfdata, col="orange", border="white", axes=TRUE)

writeSpatialShape(sfdata,"xxpoly")

  

posted @ 2017-03-02 23:25  qjtsjtu  阅读(451)  评论(0)    收藏  举报