在R中使用ggsave导出EPS格式带指定字体的图表时字体失效求助
ggplot2导出EPS时指定字体失效的解决方案
问题说明
使用ggplot2绘制图表并通过ggsave导出为EPS格式时,设置的自定义字体(如示例中的"Gill Sans MT")被忽略,同时出现半透明效果不支持的警告。原代码如下:
# Load the necessary packages library(tidyverse) library(palmerpenguins) library(extrafont) # extrafont::font_import() # to be called just once, after installing the extrafont package (or whenever you install a new font) extrafont::loadfonts(device = "pdf") # call this once per session extrafont::fonts() # get a list of fonts # Create the plot penguin_plot <- penguins |> filter(!is.na(flipper_length_mm)) |> ggplot(aes(x = flipper_length_mm, fill = species)) + geom_histogram(alpha = 0.6, position = "identity", bins = 30) + xlab("Flipper Length (mm)") + ylab("Frequency") + ggtitle("Distribution of flipper length, by species") + theme(text = element_text(family = "Gill Sans MT"), title = element_text(face = "italic")) print(penguin_plot) # Try to save as EPS with transparency ggsave( filename = "penguin_plot.eps", plot = penguin_plot, device="eps", family = "Gill Sans MT" ) # Warning message: # In grid.Call.graphics(C_rect, x$x, x$y, x$width, x$height, resolveHJust(x$just, : # semi-transparency is not supported on this device: reported only once per page
解决方案
1. 使用Cairo设备导出EPS
默认EPS设备不支持系统字体嵌入,改用cairo_ps设备可直接调用系统字体,同时处理半透明效果:
ggsave( filename = "penguin_plot.eps", plot = penguin_plot, device = cairo_ps, # 替换默认eps设备 family = "Gill Sans MT", fallback_resolution = 300 # 将半透明元素转为高分辨率位图,解决透明警告 )
- 注意:确保"Gill Sans MT"已安装在系统中,无需依赖extrafont包(可卸载extrafont简化流程)。
2. 字体嵌入验证
导出后用EPS查看工具检查字体是否正确嵌入,若仍有问题,可将非标准字体转换为PostScript兼容格式。
替代格式建议
若EPS的限制无法满足需求,推荐以下更友好的格式:
- SVG:完全支持矢量图形、自定义字体和半透明效果,导出代码:
ggsave("penguin_plot.svg", plot = penguin_plot, device = "svg") - PDF:出版行业通用格式,支持字体嵌入和透明,结合extrafont确保字体不丢失:
ggsave("penguin_plot.pdf", plot = penguin_plot, device = "pdf") extrafont::embed_fonts("penguin_plot.pdf")
内容的提问来源于stack exchange,提问作者Pedro Jorge Holanda
相关产品推荐
相关产品推荐

