Babak Kasraei
Babak Kasraei

Reputation: 87

Save a plot as a png image

I have a plot that I saved it in an object called p. This is the plot

I need to save this plot p as a png image that I like to name it, "PICP.png", in the following directory: "D:/data/results/images". I was said that I can use the following codes:

png(paste0(output_dir, "PICP_", mla, "_", var, cm, ".png", sep=""), width=6, 
    height=5, units="in", res=1200)

plot(p)

dev.off()

The problem is that I do not know how to use these codes. How should I replace the objects in these codes with my output direction, object name p, and filename: "PICP.png"?

Upvotes: 2

Views: 9155

Answers (1)

jay.sf
jay.sf

Reputation: 73612

Specify output path and file name by paste0ing output_dir and the other variables. You probably need a "/" at the end of your output_dir. Note, that in paste0 there is no sep= argument, sep='' is actually default. If p is already a plot (as I assume from your image) don't use plot(p) but print(p), or just p.

Just make it in two steps for training.

## 1. make string
output_dir <- "D:/data/results/images/"  ## note the extra slash at the end

mla <- 'foo'
var <- 'bar'
cm <- 'baz'

(to <- paste0(output_dir, "/PICP_", mla, "_", var, cm, ".png", sep=""))
# [1] "D:/data/results/images/PICP_foo_barbaz.png"  ## specified path

## 2. put string in `png` as filenmame
png(to, width=6, height=5, units="in", res=1200)

print(p)  ## or just `p`

dev.off()

Note: If you just want "PICP.png" as filename,

to <- paste0(output_dir, "PICP.png")

is sufficient.


Data:

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point()

Upvotes: 4

Related Questions