【问题标题】:Why does a PDF plot in ggplot2 not show title nor labels?为什么 ggplot2 中的 PDF 绘图不显示标题或标签?
【发布时间】:2012-11-01 11:06:52
【问题描述】:

我正在使用 ggplot2 创建一个简单的阶梯图。如果我将文件类型从 PNG 切换为 PDF,则绘图不会显示标签、刻度、标题或图例。我做错了什么?

数据:

plotData <- structure(list(iteration = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), time = c(0L, 10L, 
20L, 30L, 40L, 50L, 60L, 70L, 80L, 90L, 100L, 0L, 10L, 20L, 30L, 
40L, 50L, 60L, 70L), routes = c(6L, 6L, 5L, 3L, 3L, 3L, 3L, 3L, 
2L, 1L, 0L, 5L, 5L, 5L, 5L, 1L, 1L, 1L, 0L)), .Names = c("iteration", 
"time", "routes"), class = "data.frame", row.names = c(NA, -19L
))

代码:

    library(ggplot2)
    x_axis_breaks <- seq(10, 100, by = 10)

    png(file="plot.png",width=1280, height=1280)
    ## pdf(file="plot.pdf",width=6,height=6)
    plot <- ggplot(plotData) + geom_step(data=plotData, size = 5, 
         mapping=aes(x=time,    
         y=routes, group=iteration, colour=factor(iteration)), direction="vh")
    plot <- plot + scale_x_discrete(breaks=x_axis_breaks, name="time") + 
                   scale_y_discrete(name="#routes");
    plot <- plot + opts(axis.text.x=theme_text(size=36,face="bold"), 
                        axis.text.y=theme_text(size=36,face="bold")) +
                        scale_colour_hue(name="iteration")
    plot <- plot + opts(legend.title=theme_text(size=36,face="bold"), 
                        legend.text=theme_text(size=36,face="bold"))
    plot <- plot + opts(axis.title.x=theme_text(size=36,face="bold"),
                        axis.title.y=theme_text(size=36,face="bold"))
    plot <- plot + opts(title="network lifetime", 
             plot.title=theme_text(size=36, face="bold"))
    print(plot)
    dev.off()

如果我从“png...”切换到“pdf”,就会出现问题。数据本身绘制得很好。也许我只是错过了一些关于在 ggplot2 中生成 PDF 绘图的信息?

【问题讨论】:

  • 我看到你在这里有dev.off()(虽然它没有进入你的代码块),但是这里的症状听起来很可疑,就像忘记打电话给dev.off() ...
  • 清理了你的代码,但没有改变它的功能。在带有 R-devel 的 Ubuntu 10.04 上为我工作。你能给出sessionInfo()的结果吗?
  • 在 OSX 和 R 2.15.1 上也适用于我。你可以试试ggsave("plot.png")
  • @DrewSteen 抱歉,我在发布答案后立即看到了您的评论。 :-/

标签: r ggplot2


【解决方案1】:

这很可能是由于字体嵌入造成的。

R 默认情况下不嵌入字体,这会导致您在某些 PDF 阅读器上描述的问题。通常,您对带有大量字体的 Adob​​e Reader 上的此类图形没有任何问题,而其他阅读器可能没有很多字体(尤其是商业字体),并且通常他们会尝试用最接近的字体替换丢失的字体.有时这会失败并且您看不到任何字体。我经常在 Ubuntu 上遇到 Evince 这个问题,不仅是 R 绘图,还有任何其他没有嵌入字体的 PDF。

在 Ubuntu 上,您可以使用 pdffonts file.pdf 检查 pdf 文件的字体状态。

一些解决方案:
- 在 R 中生成 pdf 时使用 cairo_pdf 设备,通常这可以解决问题
- 使用extrafont 包嵌入所需的字体(字体必须在您的操作系统上可用),详情请参阅here

【讨论】:

    【解决方案2】:

    结合 ggplot 你应该使用ggsave() 来保存图像:

    ggsave( "plot.png", plot )
    ggsave( "plot.pdf", plot )
    ...
    

    【讨论】:

    • +1 用于提及ggsave,尽管它在后台使用pngdev.off,所以这应该可以工作。
    猜你喜欢
    • 2015-08-08
    • 2022-10-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    相关资源
    最近更新 更多