为什么ggplot2中的PDF绘图不显示标题和标签?

3
我可以帮您翻译以下内容,它与IT技术相关。您需要将简单的步骤绘图使用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()... - undefined
清理了你的代码,但没有改变其功能。在我的Ubuntu 10.04上与R-devel一起运行良好。你能给出sessionInfo()的结果吗? - undefined
1
对我来说也可以,在OSX和R 2.15.1上都可以。你可以尝试使用ggsave("plot.png") - undefined
@DrewSteen 对不起,我在回答之后看到了你的评论。 :-/ - undefined
我遇到了同样的问题,但只有在使用Adobe Acrobat查看时才出现。在Chrome中打开PDF文件则没有问题。 - undefined
2个回答

3
很可能这是由于字体嵌入的原因。R默认不会嵌入字体,这会导致您所描述的在某些PDF阅读器上出现的问题。通常情况下,在Adobe Reader中,您不会遇到此类图形的任何问题,因为它自带了许多字体,而其他阅读器可能没有很多字体(特别是商业字体),并且通常会尝试用最接近的字体替换缺失的字体。有时这种替换会失败,您将看不到任何字体。我经常在Ubuntu上使用Evince时遇到此问题,不仅是在R绘图中,而且是在任何其他未嵌入字体的PDF中。
在Ubuntu上,您可以使用“pdffonts file.pdf”命令来检查pdf文件的字体状态。
一些解决方案:
- 在R中生成pdf时使用“cairo_pdf”设备,通常可以解决问题
- 使用“extrafont”包嵌入所需的字体(该字体必须在您的操作系统上可用),请参见此处了解详细信息。

1
与ggplot结合使用时,您应该使用来保存图像:
ggsave( "plot.png", plot )
ggsave( "plot.pdf", plot )
...

+1 提到 ggsave,尽管它在内部使用了 pngdev.off,所以这应该可以工作。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接