Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a histogram from command line in R

I am trying to save a histogram to file in R from my Virtual Machine.

I use the following R code:

> 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 

I get the response: null device 1

If I just run the hist(nchar(as.character(m1$qf)),main="First name search 11-14 and 11-15",xlab="length of name") in the command line I see the correct histogram.

But when saved to pdf, I get something that looks something like this:

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

That's not the histogram I was expecting. How do I save a histogram to file?

like image 496
megv Avatar asked Dec 22 '22 04:12

megv


2 Answers

If you are new to plotting in R, I recommend getting an early start on ggplot2

library(ggplot2)
data=data.frame(x=rnorm(100))
plot=qplot(x, data=data, geom="histogram") 
ggsave(plot,file="graph1.pdf")
like image 93
Maiasaura Avatar answered Dec 24 '22 02:12

Maiasaura


R, Rscript, save histogram to file like: foobar.png:

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

Which produces a foobar.png in the same directory as the R script which contains the below image (provided you open it up in an image editor, not a word processor):

enter image description here

like image 41
Eric Leschinski Avatar answered Dec 24 '22 00:12

Eric Leschinski