如何在R绘图中嵌入自定义矢量图并设置位置、缩放与旋转
Yep, you absolutely can embed vector graphics (AI, EPS, PDF) into R plots with full control over their position, scaling, and rotation. Below are the most reliable methods using R's grid system and dedicated packages, which work for both base R plots and ggplot2:
Prerequisites
First, install and load the core packages we'll use:
install.packages(c("grImport2", "grid", "ggplot2", "gridBase")) library(grImport2) library(grid) library(ggplot2) library(gridBase)
Importing Vector Files
grImport2 is designed to handle vector graphics directly, preserving their crispness. Here's how to load different formats:
- EPS/PDF: Directly use
readPicture()(for multi-page PDFs, specify the page number):# Load an EPS file vec_img <- readPicture("your_vector_file.eps") # Load page 2 of a PDF file vec_img <- readPicture("your_vector_file.pdf", page = 2) - AI Files: Adobe Illustrator files are essentially PDF variants, but sometimes have compatibility quirks. Save your AI file as an EPS or standard PDF (via Illustrator's Save As > choose EPS/PDF with "Preserve Vector Data" enabled) for best results, then load it like the examples above.
Embedding in Base R Plots
Base R uses a separate graphics system, so we'll use gridBase to bridge it with the grid system (where our vector graphics live):
# First, create your base plot plot(1:10, 1:10, main = "Base Plot with Embedded Vector", xlab = "X", ylab = "Y") # Switch to the grid viewport tied to your base plot vps <- baseViewports() pushViewport(vps$inner, vps$figure, vps$plot) # Draw the vector graphic: customize position, size, and rotation # Use npc coordinates (0 = bottom/left, 1 = top/right) for plot-relative positioning grid.picture( vec_img, x = 0.7, y = 0.3, # Position: 70% right, 30% up from bottom-left width = 0.2, height = 0.2, # Size: 20% of plot width/height angle = 45, # Rotate 45 degrees clockwise hjust = 0.5, vjust = 0.5 # Center the graphic on the x/y point ) # Return to the base graphics system popViewport(3)
Embedding in ggplot2
Since ggplot2 is built on the grid system, embedding vector graphics is more straightforward with annotation_custom():
# Create your base ggplot p <- ggplot(mtcars, aes(wt, mpg)) + geom_point(color = "steelblue") + labs(title = "ggplot2 with Embedded Vector Graphic") # Convert the imported vector to a grid grob (graphical object) vec_grob <- pictureGrob( vec_img, width = unit(2, "cm"), height = unit(2, "cm"), # Fixed size in centimeters angle = 30 # Rotate 30 degrees clockwise ) # Add the vector graphic to the plot # Use data coordinates (matches your plot's x/y axes) here p + annotation_custom( vec_grob, xmin = 3, xmax = 5, # X range for the graphic ymin = 20, ymax = 25 # Y range for the graphic ) # Alternatively, use npc coordinates for plot-relative positioning: # p + annotation_custom( # vec_grob, # xmin = 0.7, xmax = 1, ymin = 0, ymax = 0.3, # coords = "npc" # )
Advanced Customization Tips
- Positioning: Use
unit()to mix units (e.g.,unit(1, "inch")for fixed size,unit(0.5, "npc")for plot-relative positioning). - Scaling: Adjust
width/heightingrid.picture()orpictureGrob(), or use thescaleparameter to resize proportionally. - Rotation: The
angleparameter uses clockwise degrees (e.g.,angle = -90for counter-clockwise 90 degrees). - Alignment: Use
hjust(horizontal) andvjust(vertical) to fine-tune where the graphic is anchored relative to its x/y position.
Notes to Avoid Headaches
- Always export your final plot as a vector format (like PDF) to preserve the embedded vector graphic's crispness. Use
ggsave("final_plot.pdf", p, device = "pdf")for ggplot2, orpdf("final_plot.pdf"); plot(...); dev.off()for base plots. - Avoid using bitmap-focused packages (like
magick) for this task—they'll rasterize your vector graphic, losing its scalability. - If your AI/PDF has transparency, ensure you export it with transparency enabled;
grImport2supports alpha channels.
内容的提问来源于stack exchange,提问作者passiflora

