如何将多张已有PNG图合并为指定布局?含分辨率优化问题
Hey there! Let's break down how to solve both your layout and resolution issues with your R plots—here's a step-by-step guide tailored to your needs:
First, we'll use the png package to read your existing PNG files and convert them into grid-compatible grob objects, then use gridExtra to arrange them into your desired 2-row layout (two plots side-by-side on the top, one full-width plot on the bottom):
library(png) library(gridExtra) library(grid) # Read your PNG files img1 <- readPNG("png1.png") img2 <- readPNG("png2.png") img3 <- readPNG("png3.png") # Convert images to grid grob objects g1 <- rasterGrob(img1) g2 <- rasterGrob(img2) g3 <- rasterGrob(img3) # Define the layout matrix: 2 rows, first row has 2 columns, second row spans 2 columns layout_matrix <- rbind(c(1, 2), c(3, 3)) # Arrange the plots grid.arrange(g1, g2, g3, layout_matrix = layout_matrix)
This will produce the exact layout you're targeting—top row with two side-by-side plots, bottom row with a single plot that takes up the full width.
The low-resolution issue happens because the default preview in RStudio or direct grid.arrange output uses low default resolution. To fix this, we'll explicitly create a high-resolution output device before rendering the merged plot:
# Set up a high-resolution PNG output device # Adjust width/height based on your original image dimensions (in pixels) # res = 300 gives print-quality resolution; match your original images' DPI if needed png("merged_high_res.png", width = 1600, # Example: if each top plot is 800px wide, total width is 1600 height = 1200, # Example: 600px for top row + 600px for bottom plot res = 300) # Render the arranged plot within the device grid.arrange(g1, g2, g3, layout_matrix = layout_matrix) # Close the output device to save the file dev.off()
For even more precision (to perfectly match your original image dimensions), use the pixel dimensions of your input PNGs directly:
# Get original image dimensions (width in pixels) width_img1 <- ncol(img1) width_img3 <- ncol(img3) height_img1 <- nrow(img1) height_img3 <- nrow(img3) # Set output dimensions to match total layout size png("merged_high_res_exact.png", width = width_img1 * 2, # Two top plots side-by-side height = height_img1 + height_img3, # Top row height + bottom row height res = 300) grid.draw(arrangeGrob(g1, g2, g3, layout_matrix = layout_matrix)) dev.off()
This method ensures the merged plot retains the same high resolution as your original PNGs, matching the quality you referenced.
内容的提问来源于stack exchange,提问作者lanselibai

