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 |
|---|---|---|
| PNG | png() | .png |
| JPEG | jpeg() | .jpg / .jpeg |
| pdf() | ||
| BMP | bmp() | .bmp |
| TIFF | tiff() | .tiff / .tif |
| SVG | svg() | .svg |
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.