我想绘制来自不同数据帧的两个图形,然后将它们组合成一个图形(最终图形比较复杂)。每个图都显示了两个类别变量(例如“性别”和“圆形”)上的数据子集。在两个图中,绘制的数据是相同类型的。每个数据集在这些分类变量的级别数上有所不同。
例如,下面的模拟数据绘制在3 x 2的网格中:
require(ggplot2)
set.seed(10)
# Mock data
N <- 10
rounds <- c("A","B","C")
NROUNDS <- length(rounds)
df1 <- data.frame(
Age = 1:N,Response = rnorm(N*2*NROUNDS),Sex = rep(c("M","F"),each = N),Round = rep(rounds,each = N*2)
)
# Dimension parameters
panel_width <- 2.5
panel_height <- 1.5
ylims <- c(-4,4)
units <- "in"
panel_spacing <- 0.1
plot_mar <- 0.25
total_x_margin <- panel_spacing + plot_mar*2
total_y_margin <- panel_spacing*(NROUNDS-1) + plot_mar*2
# Plot the figure
six_panel_plot <- ggplot(df1,aes(x = Age,y = Response)) +
geom_line(lwd = 2,color = "#CC79A7") +
facet_grid(rows = vars(Round),cols = vars(Sex)) +
ylim(ylims) +
theme(
panel.spacing.x = unit(panel_spacing,units),panel.spacing.y = unit(panel_spacing,plot.margin = margin(plot_mar,plot_mar,units)
) + theme_bw()
# Save the figure
ggsave("six_panel_plot.png",six_panel_plot,width = total_x_margin + panel_width*2,height = total_y_margin + panel_height*NROUNDS)
我已尝试根据每个维度中的面板数和边距大小来调整图形大小。但是,如果在4 x 2的网格上创建相似的图形,则各个面板的尺寸与先前的图形不太相同。
# Mock data
N <- 10
rounds <- c("A","C","D")
NROUNDS <- length(rounds)
df2 <- data.frame(
Age = 1:N,each = N*2)
)
# Dimension parameters
panel_width <- 2.5
panel_height <- 1.5
ylims <- c(-4,4)
units <- "in"
panel_spacing <- 0.1
plot_mar <- 0.25
total_x_margin <- panel_spacing + plot_mar*2
total_y_margin <- panel_spacing*(NROUNDS-1) + plot_mar*2
eight_panel_plot <- ggplot(df2,units)
) + theme_bw()
ggsave("eight_panel_plot.png",eight_panel_plot,height = total_y_margin + panel_height*NROUNDS)
如果在其他软件(Inkscape,Illustrator等)中对齐这些图形,则面板尺寸不相同。
如何在图形中保留各个面板的大小(而不是简单地强制第一个图形具有四行)?我想避免使用其他软件包,仅ggplot2可以吗?