简体   繁体   English

Image vs ggplot:如何绘制颜色图例?

[英]Image vs ggplot: how to plot color legend?

Hi I have a matrix 37x73 that represent one variable (moavg) gridded with a 10x10 deg spacing (-180< LON< 180 e -90 < LAT< 90). 嗨,我有一个矩阵37x73代表一个变量(moavg)网格,间距为10x10度(-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. 我想知道是否还有其他功能(也许是ggplot),这也允许我绘制颜色图例。

Many thanks 非常感谢

With regards to this answer : 关于这个答案

library(fields)
image.plot(lon, lat, moavg, col=heat.colors(8))

在此输入图像描述

PS: Please be so kind to provide a reproducible example in your question. PS:请非常友好地在您的问题中提供可重复的示例。 Here's how it works . 这是它的工作原理

For plotting gridded spatial data, the raster and rasterVis packages are also useful. 对于绘制网格化空间数据, rasterrasterVis包也很有用。

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 (eg .asc, .tif, etc.), then you can load it by giving raster() a file path, eg 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. 如果你的网格数据存在于一个文件中(例如.asc,.tif等),那么你可以通过给raster()一个文件路径加载它,例如raster('C:/path/to/moavg.asc') ,在这种情况下你不需要设置范围,因为文件应该包含这个元数据。

See ?raster and ?levelplot for more details. 有关详细信息,请参阅?raster?levelplot

Plotting with raster raster绘图 栅格图示例

Plotting with levelplot levelplot绘图 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)
            })

带叠加的levelplot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM