如何在R中从命令行保存直方图

时间:2011-12-29 23:15:39

标签: r save histogram virtual-machine

我正在尝试将直方图保存到我的虚拟机中的R文件中。

我使用以下R代码:

> pdf("graph1.pdf")
> hist(nchar(as.character(m1$qf)),main="First name search 11-14 and 11-15",
  xlab="length of     name")
> dev.off()
null device 
      1 

我收到回复:null device 1

如果我只是在命令行中运行hist(nchar(as.character(m1$qf)),main="First name search 11-14 and 11-15",xlab="length of name"),我会看到正确的直方图。

但是当保存为pdf时,我得到的东西看起来像这样:

ET
BT
/F2 1 Tf 0.00 12.00 -12.00 0.00 41.76 160.01 Tm (500000) Tj
ET
BT
/F2 1 Tf 0.00 12.00 -12.00 0.00 41.76 249.50 Tm (1000000) Tj
ET
BT
/F2 1 Tf 0.00 12.00 -12.00 0.00 41.76 342.32 Tm (1500000) Tj
ET
Q q 59.04 73.44 414.72 371.52 re W n
0.000 0.000 0.000 RG
0.75 w
[] 0 d
1 J
1 j
10.00 M
74.40 87.20 16.00 156.65 re S
90.40 87.20 16.00 20.71 re S
106.40 87.20 16.00 86.75 re S

那不是我期待的直方图。如何将直方图保存到文件?

2 个答案:

答案 0 :(得分:6)

如果您不熟悉R中的情节,我建议您尽早开始ggplot2

library(ggplot2)
data=data.frame(x=rnorm(100))
plot=qplot(x, data=data, geom="histogram") 
ggsave(plot,file="graph1.pdf")

答案 1 :(得分:2)

R,Rscript,将直方图保存为文件,如:foobar.png

library(ggplot2)
data(PlantGrowth)
png("foobar.png")
hist(PlantGrowth$weight)
dev.off()

在与包含以下图像的R脚本相同的目录中生成foobar.png(假设您在图像编辑器中打开它,而不是文字处理器):

enter image description here