【问题标题】:Add border to rasterImage为 rasterImage 添加边框
【发布时间】:2022-01-02 11:39:37
【问题描述】:

这是我使用rasterImage 创建的渐变色图例:

colfunc <- colorRampPalette(c("red", "blue"))
legend_image <- as.raster(matrix(colfunc(20), ncol=1))
plot.new()
rasterImage(legend_image, 0.9, 0, 1, 1)     
lbsq <- seq.int(0, 1, l=5)                                  
axis(4, at=lbsq, pos=1, labels=F, col=0, col.ticks=1, tck=-.05) 
mtext(lbsq, 4, -.2, at=lbsq, las=2, cex=.6)

我希望在颜色图例周围添加一个细黑色边框。我尝试在rasterImage 中添加lty = 1,但没有成功。我的问题是如何为生成的图像添加黑色边框并调整其颜色和宽度。

【问题讨论】:

    标签: r graphics raster r-raster


    【解决方案1】:

    您可以稍微增加边距并使用box()

    colfunc <- colorRampPalette(c("red", "blue"))
    legend_image <- as.raster(matrix(colfunc(20), ncol=1))
    plot.new()
    rasterImage(legend_image, -.1, -.1, 1.1, 1.1)
    box(lwd=3)
    

    你也可以玩pars。

    png('test.png', 600, 400)
    
    plot.new()
    par(new=TRUE, mar=c(5.8, 40, 4, 4))
    rasterImage(legend_image, .9, 0, 1.1, 1.1)
    box(lwd=1)
    par(mar=c(5.4, 4, 3.9, 4.8)+.1, new=TRUE)
    plot(1:10)
    
    dev.off()
    

    请注意,在使用绘图预览窗口时,这是相当不稳定的,肯定是use png() or pdf(),而不是如图所示。

    【讨论】:

    • 如果我设置rasterImage(legend_image, 0.9, 0, 1.1, 1.1),我如何调整box 的参数,使框只包含彩色区域,而不是整个绘图区域?
    • @Patrick 查看更新以获得可能的解决方案。我想你已经考虑添加一个主要情节。你可能也对我的recent answer感兴趣。
    • 谢谢。是的,这实际上是一个色彩传奇。我已经更新了我的问题。另外,我尝试了您编辑的代码,但返回“找不到对象操作”。
    • @jay.sf 很好的解决方案!当我发布我的答案时,OP尚未更新问题。现在它更有意义了。
    • @Dion 谢谢,你的解决方案也很聪明!看看?grconvertX?grconvertY's,可能对你来说很有趣,因为你似乎也喜欢低级情节。
    【解决方案2】:

    使用rect(),下面添加黑色边框。

    colfunc <- colorRampPalette(c("red", "blue"))
    legend_image <- as.raster(matrix(colfunc(20), ncol=1))
    plot.new()
    rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "black")
    rasterImage(legend_image, 0, 0, 1, 1)
    

    【讨论】:

    • 为了我的真实分析,我设置了rasterImage(legend_image, 0.9, 0, 1.1, 1.1)。是否可以调整rect 使边框仅包围彩色区域并且所有四个边的边框厚度相同?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多