如何导出50行tableGrob表格?解决导出仅显示局部问题
tableGrob() Hey there! I see you're stuck with exporting your 50-row tableGrob() as a full PNG/JPEG—only a tiny section shows up. This is super common because the default plotting device dimensions don’t account for large tables. Let’s walk through the fix step by step.
Why This Happens
The default PNG/JPEG device uses a small, fixed size (usually 7x7 inches). Your 50-row table is too tall for this space, so it gets clipped to fit the top portion. The solution is to manually set the device dimensions to match your table’s size, and tweak the table’s alignment settings to ensure everything renders correctly.
Full Working Code
Here’s a complete, adjusted version of your code that will export the full table:
library(gridExtra) library(grid) # Prepare your data as before myiris1 <- iris[1:50,1:2] # Left-aligned columns myiris2 <- iris[1:50,3:5] # Centered columns my_table <- cbind(myiris1, myiris2) # Create the tableGrob with proper alignment tg <- tableGrob( my_table, # Set column alignment for headers cols.just = c("left", "left", "center", "center", "center"), # Set content alignment for table cells theme = ttheme_default( core = list( fg_params = list(hjust = c(0, 0, 0.5, 0.5, 0.5)), padding = unit(c(2, 2), "mm") # Add small padding to prevent crowded text ), colhead = list( fg_params = list(hjust = c(0, 0, 0.5, 0.5, 0.5)) ) ), rows = NULL # Remove default row numbers (keep this line if you want row numbers) ) # Calculate the exact height needed for your table total_table_height <- sum(tg$heights) + unit(4, "mm") # Add extra margin for safety # Export to PNG (adjust width/height/res as needed) png( filename = "full_iris_table.png", width = 8, # Width in inches (adjust based on your column width) height = as.numeric(total_table_height) / 72 * 1.1, # Convert to inches, add 10% buffer res = 300 # Higher resolution = sharper image ) grid.draw(tg) dev.off() # Export to JPEG (just swap png() with jpeg()) jpeg( filename = "full_iris_table.jpg", width = 8, height = as.numeric(total_table_height) / 72 * 1.1, res = 300 ) grid.draw(tg) dev.off()
Key Adjustments Explained
- Column Alignment: The
cols.justandhjustparameters ensure your first two columns stay left-aligned, and the rest are centered (applies to both headers and table content). - Dynamic Height Calculation: Instead of guessing the height, we calculate the exact size of the table with
sum(tg$heights)—this works for any number of rows, not just 50. - Device Dimensions: The
widthandheightarguments inpng()/jpeg()are set to fit the table exactly, with a small buffer to avoid clipping. - Resolution:
res=300ensures the exported image is crisp, not pixelated.
Troubleshooting Tips
- If text still looks crowded: Increase the
paddingvalue inttheme_default(). - If columns are too narrow: Adjust the
widthparameter in the export device, or usetg$widthsto manually set column widths (e.g.,tg$widths[1] <- unit(2, "inches")).
内容的提问来源于stack exchange,提问作者LLL

