Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

r - Combine ggplots but fix the size/ratio of the plots

I have two plots that I combine. arrangeGrob() squeezes them so that the size of the new image is the same as one alone. How can I arrange them while preserving the ratio/size?

require(ggplot2)
require(gridExtra)

dat <- read.csv("http://www.ats.ucla.edu/stat/data/fish.csv")

frqncy <- as.data.table(table(dat$child))#
frqncy$V1 <- as.numeric(frqncy$V1)

plot1 <- ggplot(frqncy, aes(x=V1, y= N)) +
    geom_histogram(stat="identity", binwidth = 2.5)
plot2 <- ggplot(frqncy, aes(x=V1, y= N)) +
    geom_density(stat="identity")

plot <- arrangeGrob(plot1, plot2)

Plot looks like

Plots become smaller when combined

I have not found any parameter in ggplot() or arrangeGrob() that fixes the ratio of the input.

Edit: Additional complications arise from the definition of axis labels in arrangeGrob(), i.e.

plot <- arrangeGrob(plot1, plot2, left="LHS label")

Then the new file will not automaticall shrink to the minimum height/width combination of plot1 and plot2.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

there are several other options, depending on what you want*

library(ggplot2)
p = qplot(1, 1)
grid.arrange(p, p, respect=TRUE) # both viewports are square
grid.arrange(p, p, respect=TRUE, heights=c(1,2)) # relative heights

p1 = p + theme(aspect.ratio=3)
grid.arrange(p,p1, respect=TRUE) # one is square, the other thinner

*: the aspect ratio is often not a well-defined property of plots (unless set manually), because the default is to extend the plot to the available space defined by the plot window/device/viewport.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...