我想绘制来自不同数据帧的两个图形,然后将它们组合成一个图形(最终图形比较复杂)。每个图都显示了两个类别变量(例如“性别”和“圆形”)上的数据子集。在两个图中,绘制的数据是相同类型的。每个数据集在这些分类变量的级别数上有所不同。
例如,这里的模拟数据绘制在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, units),
plot.margin = margin(plot_mar, plot_mar, 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", "B", "C", "D")
NROUNDS <- length(rounds)
df2 <- 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
eight_panel_plot <- ggplot(df2, 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, units),
plot.margin = margin(plot_mar, plot_mar, plot_mar, plot_mar, units)
) + theme_bw()
ggsave("eight_panel_plot.png", eight_panel_plot,
width = total_x_margin + panel_width*2,
height = total_y_margin + panel_height*NROUNDS)
如果我在其他软件(Inkscape,Illustrator等)中对齐这些图形,则面板尺寸不相同。
我如何在图形中保留单个panels的大小(而不是简单地使第一个图形具有四行)?我想避免使用其他软件包,仅ggplot2可以吗?
我没有仅适用于ggplot的解决方案,但我将使用ggplot本身依赖的某些软件包(grid和gtable),因此不需要额外的下载。我假设所需的单位以英寸为单位定义,但是很容易更改。
library(grid)
# As per your post
panel_width <- 2.5
panel_height <- 1.5
# Convert plot to gtables
plots <- list(p8 = ggplotGrob(eight_panel_plot),
p6 = ggplotGrob(six_panel_plot))
plots <- lapply(plots, function(gt) {
# Find the positions of panels
panel_x <- unique(panel_cols(gt)$l)
panel_y <- unique(panel_rows(gt)$t)
# Change the sizes of these positions
gt$widths[panel_x] <- unit(panel_width, "inch")
gt$heights[panel_y] <- unit(panel_height, "inch")
gt
})
ggsave("test1.png", plot = plots[[1]])
ggsave("test2.png", plot = plots[[2]])
test1.png:
test2.png:
您可以尝试egg :: set_panel_size()