How to save a histogram from command line in R
22,325
Solution 1
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")
Solution 2
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):
Comments
-
megv almost 2 years
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?
-
Dason over 12 yearsThe code you posted should save the histogram into a pdf file in your current working directory. You can check your working directory by using the function getwd(). Do you not get the pdf saved? What exactly is the problem?
-
Maiasaura over 12 yearsTo see files in your current directory, run a dir()
-
John Colby over 12 yearsWhat VM are you running?
-
-
Carl Witthoft over 12 yearsI'll admit to being an old fogy who all too often uses the basic
plot
stuff, but ggplot and ggplot2 are absolutely the way to go.