How to change the background colour of a subplot/i

2020-06-23 08:24发布

I'd like to add a subplot to an existing plot in R. The subplot (inset) should have a different background color. I tried the following:

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

In the help of subplot() it says for pars:

a list of parameters to be passed to par before running fun.

It seems to be very difficult to change the backgroundcolor of a plot, since the graphic parameter has a different meaning in plot(). So one has to set the background color using par(). but why does this not work for subplot? (I also tried to put the plot-function into a extaernal function that calls par() and plot(), but this did not help).

Why does subplot not work properly?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-06-23 08:44

The bg argument of par change the background color of the device not of the plot. Since you're just merely adding a plot to an already opened and used device, this is not a possibility (because of the pen-and-paper way base plots are drawn). Instead what you can do (building on this previous answer) is the following:

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

Edit: if you want the area containing also the annotations to be blue, the other solution i see would be to draw the rectangle prior to drawing the subplot (using the coordinates you gave to the subplot function):

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")
查看更多
登录 后发表回答