controlling column widths for side by side base graphic and ggplot2 graphic

早过忘川 提交于 2019-12-12 01:59:13

问题


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



来源:https://stackoverflow.com/questions/14358526/controlling-column-widths-for-side-by-side-base-graphic-and-ggplot2-graphic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!