我的 R 代码以交互模式创建绘图,但不是作为脚本(在 Windows 上)

My R code creates plots in interactive mode, but not as a script (on Windows)

此代码 运行 在交互模式下很好,并创建了指定的绘图。然而,当运行作为脚本时产生的情节是空白的。有没有一种方法可以将其编码为既可以作为脚本又可以交互地工作?我正在使用 RStudio 版本 0.98.1091,运行ning 在 32 位 Windows 7 上。这作为脚本在 Linux.

上运行良好
library(ggplot2)

genes <- data.frame(Genes=c("A","B","C","D","E"),
                    Expression=c(1,7.6,100,2,67)
                    )

png("genes_with_legend.png")
qplot(Genes,Expression,data=genes,stat="identity",geom="bar",fill=factor(Genes))
dev.off()

png("genes_without_legend.png")
ggplot(genes,aes(Genes,Expression)) + geom_bar(stat="identity",fill=seq_along(factor(genes$Genes)),legend.position="none")
dev.off()

将绘图保存到变量,然后打印它:

library(ggplot2)

genes <- data.frame(Genes=c("A","B","C","D","E"),
                    Expression=c(1,7.6,100,2,67)
                    )

png("genes_with_legend.png")
plt = qplot(Genes,Expression,data=genes,stat="identity",geom="bar",fill=factor(Genes))
print(plt)
dev.off()

png("genes_without_legend.png")
plt = ggplot(genes,aes(Genes,Expression)) + geom_bar(stat="identity",fill=seq_along(factor(genes$Genes)),legend.position="none")
print(plt)
dev.off()

值 "autoprint" 在交互模式下。例如,在交互模式下键入 genes 后,数据帧立即打印到屏幕上。但是,您不希望在没有 print 语句的情况下将其打印到文件中。同样, 也需要在非交互模式下打印。显式打印绘图将适用于交互和 "script" 模式。

这是一个很常见的错误,已在 R-FAQ 7.22 中列出。