将ggplot2条形图保存为pdf时的空白文件(Windows 7)

时间:2013-01-23 07:02:08

标签: r ggplot2

  

可能重复:
  Plotting and saving PDFs in a loop

新手的问题。 我的标签分隔输入数据如下所示:

x y
1 50
2 25
3 60
4 25
5 90
6 100

这是我的代码文件“code.R”:

data <- read.table("input",header=T,sep="\t")
pdf("output.pdf")
ggplot (data,aes(x=x,y=y) + geom_bar(stat="identity")
dev.off()

我使用下面的命令运行代码,并且不会收到任何错误消息:

source("code.R")

代码生成“output.pdf”文件,但它是空白的(当我想打开它时出错。)

当我在R端子中手动输入上述代码的第1行和第2行时,图形在图形设备中看起来是正确的。

当我在文件中写下面的行并运行文件时,没有任何反应(没有错误,没有图形设备窗口)

data <- read.table("input",header=T,sep="\t")
ggplot (data,aes(x=x,y=y)) + geom_bar(stat="identity")

输入和代码文件的行结尾都是Windows格式。 我也试过了data <- as.data.frame(read.table(...)),但它什么都没改变。 我真的不明白我的代码中有什么问题...

任何建议和解释都会很棒! 谢谢!

1 个答案:

答案 0 :(得分:1)

你错过了ggplot调用的近括号。

这一行:

ggplot (data,aes(x=x,y=y) + geom_bar(stat="identity")

应该是:

ggplot (data,aes(x=x,y=y)) + geom_bar(stat="identity")

或者您可以尝试使用ggsave()代替pdf()dev.off():

ggplot (data,aes(x=x,y=y)) + geom_bar(stat="identity")
ggsave("output.pdf")

不要混用这两种方法。