Usually, in R, I'm able to use xpd = NA
to add elements to an existing plot that extend outside of the plot region.
However, in this case I am trying to add violin plots or box plots, and this approach is not working.
library(vioplot)
# generate some data
dat <- replicate(10, rnorm(20), simplify = FALSE)
range(unlist(dat))
# first example, with all data within range
plot.new()
plot.window(xlim = c(1, 10), ylim = c(-5,5))
axis(1)
axis(2)
vioplot(dat, add = TRUE, frame.plot = FALSE)
Now trying to plot outside of the plotting region.
plot.new()
par(oma = c(3,3,3,3))
plot.window(xlim = c(1, 10), ylim = c(-10, -2))
axis(1)
axis(2)
vioplot(dat, add = TRUE, frame.plot = FALSE, xpd = NA)
boxplot(dat, add = TRUE, frame.plot = FALSE, xpd = NA)
# plot points to prove that this works with some elements
points(1:10, sapply(dat, median), xpd = NA)
Any ideas on how to add violin plots or box plots in such a scenario?
With box plots, I could of course easily draw them myself with rect()
and segments()
, but violin plots are more complicated.
CodePudding user response:
You can set xpd=NA
globally with par(xpd=NA)
, draw what you need with vioplot()
or boxplot()
and then restore the default xpd
value with par(xpd=F)
.
Looking in the source code, vioplot()
ignores all graphical parameters (including xpd
) passed to it if they are NA
. You could in theory use xpd=T
but this is unfortunately not passed to all the lower level drawing functions. boxplot()
(or rather its workhorse bxp()
) does not seem to pass xpd
to any of the drawing functions it uses.