图像与ggplot:如何绘制颜色传说? [英] Image vs ggplot: how to plot color legend?

查看:122
本文介绍了图像与ggplot:如何绘制颜色传说?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我有一个矩阵37x73,表示一个以10x10度间距(-180
  image(LON,LAT,moavg)

但我无法显示颜色栏。我想知道是否有另一个功能可以做到这一点(也许是ggplot),让我也可以绘制颜色图例。



非常感谢

解决方案

对于绘制网格化空间数据,栅格 rasterVis











$ b library(rasterVis)#这也会加载光栅包

#从一个虚拟数据矩阵中创建一个光栅
m< - matrix(runif(36 * 18) ),ncol = 36)
r < - 光栅(m)

#设置对象的范围
extent(r)< - c(-180,180, (r,margin = FALSE)

#plot with rasterVis
plot(r)

# b $ b

如果您的网格数据存在于文件中(例如.asc,.tif等),那么您可以通过给出 raster()文件路径加载它,例如 raster('C:/path/to/moavg.asc'),你不需要在这种情况下设置范围,因为文件应该包含这个元数据。



有关更多详细信息,请参见?raster ?levelplot


$ b 使用栅格 绘制



使用 levelplot






编辑



评论,这里是覆盖多边形的一种方式:

  library(maps)
levelplot(r,xlab = 'longitude',ylab ='latitude',margin = FALSE,
panel = function(x,y,...){
panel.levelplot(x,y,...)
mp < - map(world,plot = FALSE,fill = TRUE)
lpolygon(mp $ x,mp $ y)
})


Hi I have a matrix 37x73 that represent one variable (moavg) gridded with a 10x10 deg spacing (-180< LON< 180 e -90 < LAT< 90). I am able to plot it using image

image(LON, LAT, moavg)

but I can't display the colour bar. I would like to know if there is another function to do that (maybe ggplot) that allows me also to plot the colour legend.

Many thanks

解决方案

For plotting gridded spatial data, the raster and rasterVis packages are also useful.

Here are a couple of examples:

library(rasterVis) # this will also load the raster package

# Create a raster from a matrix of dummy data
m <- matrix(runif(36*18), ncol=36)
r <- raster(m)

# Set the extent of the object
extent(r) <- c(-180, 180, -90, 90)

# plot with raster
plot(r)

# plot with rasterVis
levelplot(r, margin=FALSE)

If your gridded data exists in a file (e.g. .asc, .tif, etc.), then you can load it by giving raster() a file path, e.g. raster('C:/path/to/moavg.asc'), and you shouldn't need to set the extent in that case since the file should contain this metadata.

See ?raster and ?levelplot for more details.

Plotting with raster

Plotting with levelplot


EDIT

To address the extension to this question found in the comments, here is one way to overlay a polygon:

library(maps)
levelplot(r, xlab='longitude', ylab='latitude', margin=FALSE,
            panel = function(x, y, ...) {
              panel.levelplot(x, y,  ...)
              mp <- map("world", plot = FALSE, fill=TRUE)
              lpolygon(mp$x, mp$y)
            })

这篇关于图像与ggplot:如何绘制颜色传说?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆