# 1 Goal

The goal of this tutorial is to show how to store our plots made in R in different formats. Available formats cover some of this extensions: pdf, png, jpeg. The logic will always be the same: open a canvas in the format we want, plot inside the canvas and then close the canvas in order to save the file.

# 2 Data import and plot

library(ggplot2)
# In this tutorial we are going to use the iris dataset
data("iris")
str(iris)
## 'data.frame':    150 obs. of  5 variables:
##  $Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... ##$ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... ##$ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  \$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
# We save our plot in an object that we can use later in our script
my_plot <- ggplot() + geom_point(data = iris, aes(x = Petal.Width, y = Petal.Length, colour = Species)) +
ggtitle("Petal from iris plants") + xlab("Petal Width") + ylab("Petal Length") +
theme(plot.title = element_text(hjust = 0.5))

# This action prints the plot
my_plot

# 3 Save the plot in pdf

# We call the pdf object introducing a filename
# We can define the size of the pdf
# By default the pdf that is created is 7 by 7 inches
# We plot on the pdf and then we close the connection to create the file
pdf("my_plot.pdf")
my_plot
dev.off()
## quartz_off_screen
##                 2

# 4 Save the plot as image

# The same logics applied to png applies to bmp, jpeg and tiff.
# Check ?png for further information
png("my_plot.png")
my_plot
dev.off()
## quartz_off_screen
##                 2

# 5 Conclusion

In this tutorial we have learnt how to save our plots in different formats from pdf to several image formats.