【问题标题】:Copying plot with type=n in R to PDF doesn't copy plot points, only it's lines are shown in output pdf将 R 中 type=n 的绘图复制到 PDF 不会复制绘图点,只有它的线条显示在输出 pdf 中
【发布时间】:2014-01-24 13:59:44
【问题描述】:

我在将以下随机数据示例复制到 pdf 时遇到了一个小问题。我意识到可以将其复制为 png,也可能复制为其他位图格式,但不能复制为 pdf。

我试图通过这个例子学习如何在一个情节上绘制“男性”和“女性”,并用不同的颜色等显示它们。 我的设备是 windows。


    x<- rnorm(100)
    y<- x+rnorm(100)
    g<- gl(2,50)
    g<- gl(2,50, labels = c("Male","Female"))
    str(g)
    plot(x,y)

    # Plot function of (x,y) above will display it but it's not clear who is women and who is men, so I do following steps to plot it with different colors.
    # Plotting it with type="n".

    plot(x,y, type="n")
    points(x[g=="Female"], y[g=="Male"], col = "blue")
    points(x[g=="Male"], y[g=="Female"], col = "green", pch=19)
    fit<- lm(x~y)
    abline(fit)

    # Now I try to Copy it to png and that works fine.
    dev.copy(png,"myfile.png",width=8,height=6,units="in",res=100)
    dev.off()

    # Now to pdf. This example doesn't work at all abd pdf won't even open in my pdf viewer.
    pdf("myfile.pdf",width=8,height=6)
    dev.off()

    # So I try this and I am able to open it but only "abline" and "x" and "y" are present not the points I specified for males and females.
    dev.copy2pdf(file="Examp1.pdf",out.type = "pdf")
    dev.off()

你知道为什么会这样吗? PNG可能就足够了,但它有缺陷。那么知道如何将它复制到 R 中的 pdf 中吗?

感谢您的回答。

【问题讨论】:

  • 来自?dev.copy 的注意事项:“请注意,这些函数复制设备区域而不是绘图”
  • 再次从手册“复制到的设备成为当前设备”。可能这是否意味着在 copy2pdf 中您尝试复制 png 设备?因为它是上次复制的...请注意,如果我运行您的代码,我会收到此错误消息“只能从屏幕设备打印”

标签: r pdf plot


【解决方案1】:

只需使用:

pdf("myfile.pdf",width=8,height=6)
    plot(x,y, type="n")
    points(x[g=="Female"], y[g=="Male"], col = "blue")
    points(x[g=="Male"], y[g=="Female"], col = "green", pch=19)
    fit<- lm(x~y)
    abline(fit)
dev.off()

说明:这将打开一个pdf 设备,对其进行绘图并关闭该设备。

【讨论】:

    【解决方案2】:

    正如我在评论中报告的那样,这很好用,因为我将原始屏幕设备而不是复制的 png 设备复制到 pdf 设备中。请注意,设备复制功能只能复制屏幕设备,当您复制设备时,它将成为当前设备。

    windows()
    x<- rnorm(100)
    y<- x+rnorm(100)
    g<- gl(2,50)
    g<- gl(2,50, labels = c("Male","Female"))
    str(g)
    plot(x,y)
    
    plot(x,y, type="n")
    points(x[g=="Female"], y[g=="Male"], col = "blue")
    points(x[g=="Male"], y[g=="Female"], col = "green", pch=19)
    fit<- lm(x~y)
    abline(fit)
    
    dev.copy(png,"myfile.png",width=8,height=6,units="in",res=100)
    dev.off()
    # How many devices are in list? 
    print (dev.list())
    
    # I must copy only screen device, that there is the previous one
    dev <- dev.prev() 
    
    # Now it works
    dev.copy2pdf(file="Examp1.pdf",out.type = "pdf")
    dev.off()
    

    【讨论】:

      猜你喜欢
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 2019-03-28
      • 1970-01-01
      相关资源
      最近更新 更多