【问题标题】:How to change the background colour of a subplot/inset in R?如何更改 R 中子图/插图的背景颜色?
【发布时间】:2013-06-10 21:46:51
【问题描述】:

我想在 R 中的现有图上添加一个子图。子图(插图)应该有不同的背景颜色。我尝试了以下方法:

#install.packages("TeachingDemos", dependencies=T)
library(package="TeachingDemos")

d0 <- data.frame(x = rnorm(150, sd=5), y = rnorm(150, sd=5))
d0_inset <- data.frame(x = rnorm(1500, sd=5), y = rnorm(1500, sd=5))

plot(d0)
subplot( 
  fun = plot(
    d0_inset
    , col = 2
    , pch = '.'
    , mgp = c(1,0.4,0)
    , ann = F
    , cex.axis=0.5
  ) 
  , x = grconvertX(c(0.75,1), from='npc')
  , y = grconvertY(c(0,0.25), from='npc')
  , type = 'fig'
  , pars = list(
             mar = c(1.5,1.5,0,0) + 0.1
             , bg = "blue"              # this should change the background color
           )
)

subplot() 的帮助下,它表示pars

运行fun之前要传递给par的参数列表。

更改绘图的背景颜色似乎非常困难,因为图形参数在plot() 中具有不同的含义。所以必须使用par() 设置背景颜色。但是为什么这不适用于subplot? (我还尝试将绘图函数放入调用par()plot() 的外部函数中,但这没有帮助)。

为什么子图不能正常工作?

【问题讨论】:

    标签: r background plot subplot insets


    【解决方案1】:

    parbg 参数更改了设备的背景颜色,而不是绘图的背景颜色。由于您只是将绘图添加到已打开和使用的设备,因此这是不可能的(因为绘制了base 绘图的笔和纸方式)。相反,您可以执行以下操作(基于 this previous answer):

    plot(d0)
    subplot(fun = {plot(d0_inset, mgp = c(1,0.4,0), ann = F, cex.axis=0.5);
                   rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "blue");
                   points(d0_inset, col=2, pch=".") }, 
            x = grconvertX(c(0.75,1), from='npc'), 
            y = grconvertY(c(0,0.25), from='npc'), 
            pars = list(mar = c(1.5,1.5,0,0) + 0.1), type="fig")
    

    编辑:如果您希望包含注释的区域也为蓝色,我看到的另一个解决方案是在绘制子图之前绘制矩形(使用您给子图的坐标功能):

    plot(d0)
    rect(grconvertX(0.75, from='npc'), grconvertY(0, from='npc'),
         grconvertX(1, from='npc'), grconvertY(0.25, from='npc'), 
         col="blue", border=NA)
    subplot(fun = plot(d0_inset, mgp = c(1,0.4,0), ann = F, 
                        cex.axis=0.5,col=2, pch=".") , 
            x = grconvertX(c(0.75,1), from='npc'), 
            y = grconvertY(c(0,0.25), from='npc'), 
            pars = list(mar = c(1.5,1.5,0,0) + 0.1), type="fig")
    

    【讨论】:

    • 这只会改变绘图区域的颜色。轴标签没有新背景。还有没有办法找出整个 subplot-Area 的尺寸?
    猜你喜欢
    • 2023-02-15
    • 1970-01-01
    • 2018-06-11
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2020-08-21
    • 2016-01-15
    相关资源
    最近更新 更多