为什么在R中源代码包含`png(...)`和`dev.off()`时会出现空白图形?

6l7fqoea  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(177)

)和dev. off()来将图写入文件。代码是这样的

allWeeks = data.frame(weekInYear = 1:53,
                  user2013 = sample(1:100, 53),
                  user2014 = sample(1:100, 53),
                  user2015 = sample(1:100, 53),
                  job2013 = sample(1:100, 53),
                  job2014 = sample(1:100, 53),
                  job2015 = sample(1:100, 53))

allWeeks[30:53, c('user2015', 'job2015')] = NA

melted = melt(allWeeks[ , c('weekInYear', 'user2015', 'job2015')], id = 'weekInYear')
pic1 = 'output/allWeek2015.png'
png(width = 600, height = 300, file = pic1)
ggplot(melted, aes(weekInYear, value, colour = variable)) +
        geom_line()
dev.off()

melted = melt(allWeeks[ , c('weekInYear', 'user2013', 'user2014', 'user2015')], id = 'weekInYear')
pic2 = 'output/allWeekUser.png'
png(width = 600, height = 300, file = pic2)
ggplot(melted, aes(weekInYear, value, colour = variable)) +
        geom_line()
dev.off()

melted = melt(allWeeks[ , c('weekInYear', 'job2013', 'job2014', 'job2015')], id = 'weekInYear')
pic3 = 'output/allWeekJob.png'
png(width = 600, height = 300, file = pic3)
ggplot(melted, aes(weekInYear, value, colour = variable)) +
        geom_line()
dev.off()

当我选择所有代码并单击run时,它运行得很好,并显示了一些关于绘制数据中NA的警告消息。
当我点击source时,没有消息,图片也是空白的。任何帮助的感激请…
更新:替换为ggsave(pic1, width = 3, height = 1.5),现在没有空白问题。但是ggsave()似乎使用了不合理的比例和字体大小...查看图片:左保存png()dev.off()与右保存为ggsave()。我错过了什么参数吗?任何帮助的感激请

j2datikz

j2datikz1#

我也有同样的问题。您可以尝试先将绘图作为对象,然后在dev.off()之前将print()用于这个新的虚拟绘图对象。

allWeeks = data.frame(weekInYear = 1:53,
                      user2013 = sample(1:100, 53),
                      user2014 = sample(1:100, 53),
                      user2015 = sample(1:100, 53),
                      job2013 = sample(1:100, 53),
                      job2014 = sample(1:100, 53),
                      job2015 = sample(1:100, 53))
    
    allWeeks[30:53, c('user2015', 'job2015')] = NA
    
    
    melted = melt(allWeeks[ , c('weekInYear', 'user2015', 'job2015')], id = 'weekInYear')
    pic1 = 'output/allWeek2015.png'
    png(width = 600, height = 300, file = pic1)
    dummy_plot <- ggplot(melted, aes(weekInYear, value, colour = variable)) +
            geom_line()
    print(dummy_plot)
    dev.off()

相关问题