【问题标题】:Image vs ggplot: how to plot color legend?Image vs ggplot:如何绘制颜色图例?
【发布时间】:2014-02-10 18:18:50
【问题描述】:

您好,我有一个 37x73 的矩阵,它表示一个变量 (moavg),网格化为 10x10 度间距 (-180

image(LON, LAT, moavg)

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

非常感谢

【问题讨论】:

    标签: r image plot ggplot2 legend


    【解决方案1】:

    对于绘制网格化空间数据,rasterrasterVis 包也很有用。

    这里有几个例子:

    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)
    

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

    有关详细信息,请参阅 ?raster?levelplot

    raster绘图

    levelplot绘图


    编辑

    为了解决在 cmets 中发现的这个问题的扩展,这里是覆盖多边形的一种方法:

    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)
                })
    

    【讨论】:

    • 嗨,太好了!如何设置轴名称并覆盖世界地图?我尝试使用 map(add=T) bat 它不起作用..
    • 您好,不如根据网格字段的间距来缩放地图呢?谢谢
    • 不太清楚你的意思。如果您在 SO 上找不到相关答案,可能会将其作为一个新问题发布。如果您询问如何调整图例更改颜色的点,请使用at 参数提供数字向量(如?lattice::levelplot 中所述)。
    【解决方案2】:

    关于this answer

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

    PS:请在您的问题中提供一个可重复的示例。 Here's how it works

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 2021-11-13
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 2013-09-02
      相关资源
      最近更新 更多