[英]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. 对于绘制网格化空间数据,
raster
和rasterVis
包也很有用。
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
绘图
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)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.