【问题标题】:How to save a histogram from command line in R如何从R中的命令行保存直方图
【发布时间】:2012-01-30 06:27:17
【问题描述】:

我正在尝试从我的虚拟机将直方图保存到 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

这不是我期望的直方图。如何将直方图保存到文件中?

【问题讨论】:

  • 您发布的代码应该将直方图保存到您当前工作目录中的 pdf 文件中。您可以使用函数 getwd() 检查您的工作目录。你没有保存pdf吗?究竟是什么问题?
  • 要查看当前目录中的文件,请运行 dir()
  • 你在运行什么虚拟机?

标签: r save histogram virtual-machine


【解决方案1】:

如果您不熟悉 R 绘图,我建议您尽早开始使用 ggplot2

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

【讨论】:

  • 我承认自己是一个老顽固,经常使用基本的plot 东西,但 ggplot 和 ggplot2 绝对是要走的路。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2012-07-06
    • 2012-08-23
    • 1970-01-01
    • 2017-12-12
    • 2011-06-27
    • 1970-01-01
    • 2014-01-26
    • 2018-01-30
    • 1970-01-01
    相关资源
    最近更新 更多