controlling column widths for side by side base gr

2019-08-19 05:53发布

问题:

@Ricardo Saporta has proposed here an easy way to combine base graphics and ggplot graphics in a multiple plots figure.

I use this way to plot a base graphic at left and a ggplot graphic at right which actually contains two graphics (this is an artifical example, not a real one, but it has the same structure as my real example) :

library(ggplot2)
library(gridExtra)
library(plotrix)

Mvalues <- matrix(rpois(9,1), ncol=3)
Mcolors <- matrix(rpois(9,5), ncol=3)

par(mfrow=c(1,2))
color2D.matplot(x=Mvalues, show.values=2, cellcolors=Mcolors, 
    xlab="x", ylab="y", axes=FALSE, vcex=0.4)
gg2 <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge") 
ta <- do.call(arrangeGrob, list(gg2,gg2))
vp.Left <- viewport(height=unit(1, "npc"), width=unit(0.5, "npc"), 
    just="left", y=0.5, x=0.5)
print(ta, vp=vp.Left)

Very nice. But now I want the base graphic to have a larger width than the ggplot graphics. How to do ? I have unsuccessfully tried to do so with the layout() function.

回答1:

Here you go:

Use layout with different widths. Notice how I define the first column to be double the width of column 2:

layout(matrix(c(1, 2, 1, 3), ncol=2, byrow=TRUE), widths=c(2, 1))

Set up the graphics

layout(matrix(c(1, 2, 1, 3), ncol=2, byrow=TRUE), widths=c(2, 1))
color2D.matplot(x=Mvalues, show.values=2, cellcolors=Mcolors, 
                                xlab="x", ylab="y", axes=FALSE, vcex=0.4)
gg2 <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge") 
ta <- do.call(arrangeGrob, list(gg2,gg2))

Now define the viewport. Your code was almost there. I simply modified it to be right justified, and changed the width to be 33%:

vp <- viewport(height=unit(1, "npc"), width=unit(0.33, "npc"), 
               just="right", x=1, y=0.5)

Finally, print the remaining graphic:

print(ta, vp=vp)