📚 R Programming Tutorial

R Programming

Learn R programming concepts with simple explanations, examples, techniques and practical notes.

← Back to R Programming

Saving Graphs to Files

R graphics can use different display devices. The screen is the default one. To save a graph as a file, you need to choose a different device. Let us start by learning the basics of R graphics devices.

R Graphics Devices

In R, graphics devices are used to save plots as files like PNG, PDF, JPEG, etc.

Common Devices:

Format Function File Extension
PNGpng().png
JPEGjpeg().jpg / .jpeg
PDFpdf().pdf
BMPbmp().bmp
TIFFtiff().tiff / .tif
SVGsvg().svg
General Format:
device_function("filename", width=..., height=...)
Example:
png("my_plot.png", width=600, height=400)

Saving the Graphs

In R, you can save graphs using device functions in various formats like PNG, PDF, JPEG, etc.

Example: Save to PNG
> # Open PNG device
> png("cricket_plot.png", width=600, height=400)

> # plot a graph
> x <- c(1, 2, 3, 4, 5)
> y <- c(2, 4, 3, 6, 5)
> plot(x, y, main="Score Plot", xlab="Overs", ylab="Runs", type="b", col="red", pch=16, lwd=2)

> # Close the device and save the file
> dev.off()
Output:

The above code saves the graph as cricket_plot.png with a width of 600 px and a height of 400 px. The dev.off() function closes the device and saves the file.