Saving plots to a file

In this section, we will take a look at the different methods available of saving your plots. Most of these concepts apply to all plots realized in R although we will also consider the ggsave() function that is specific to the ggplot2() package. In R, there are three ways that you can use to save created plots:

  • Saving the plot manually by way of the device window system (could be different between operating systems)
  • Saving the plot to a file without rendering the plot
  • Saving the plot after rendering the plot

We will take a look at the different methods in the upcoming sections. Just keep in mind that when you save a file as a plot, the file with the specified filename will be saved in your working directory. Be careful since, if you already have a file with the same name, it will be overwritten without any warnings from R, so if you run the code in these examples, just verify that your working directory does not contain files with the same name as the plot that we will save.

Saving the plot manually

An easy way to save your plot to a file is to do it manually in the R GUI. After running the code that generates the plot, R will render the plot in a device window, which will open in the R console. At this point, by selecting the graph window, you will have access to the dedicated menu, where, in the File section, you can find the saving options. You can choose between different file formats, such as PNG, JPEG, and PDF, as well as save the plot in the clipboard or print the plot directly. Alternatively, you can also right-click on the plot itself, and you will be able to also copy the plot to the clipboard or save it as a metafile or bitmap.

Saving the plot to a file without rendering it

In some cases, you may want to save the file directly from code without manually saving it. This approach can, for instance, be very useful if you have scripts running and producing standard plots. In this case, you can embed code in your scripts to do analysis and produce standard plots. There are several different functions that can save your plot in a variety of formats. What these functions do is open a graphical device and render your plot in the device until the device is closed. For this reason, the plot will not be rendered on the R console but will be saved directly in the graphical device. There are several functions that allow you to create different file formats, the most important of them being PNG, PDF, and JPEG, which are listed here with some of their main arguments:

  • png(filename, width, height)
  • pdf(file, width, height)
  • jpeg(filename, width, height)

You can find a complete list of the devices available by running ?Devices.

All these functions work in a very similar way so, in our examples, we will take a look at the pdf() function.

Saving a single plot

If you want to save, for instance, a plot in a PDF file, you can use the following command:

pdf("myFile.pdf")
ggplot(data=cont, aes(x=x, y=y, col=factor(group))) + geom_point()
dev.off()

This code will create a file called myFile.pdf in the current working directory, in which the plot will be saved. Keep in mind that even if you are using the pdf() function, you will need to specify the file extension in the function; otherwise, the file created will not be saved as PDF. After running the pdf() function, simply run the plot code you want to include in myFile.pdf, and it will be saved to the file. After you have run all the plots you need, you can close the device with dev.off(). The first part of the code, where we used the pdf() function, is the part that should be changed if you want to create a different file, while the remaining part of the code is independent of the type of device selected. So, for instance, if you wanted to create a PNG file, you can do so in the following way:

png("myFile.png")
ggplot(data=cont, aes(x=x, y=y, col=factor(group)))+geom_point()
dev.off()

In the simple examples that we have considered, we have been working on the console when creating the file. Alternatively, you can also include such code in a script that is run automatically to create plots. So, if you are running the code as a script, you will need to explicitly print the plot, as shown here:

png("myFile2.png")
print(ggplot(data=cont, aes(x=x, y=y, col=factor(group))) + geom_point())
dev.off()

Saving multiple plots on the same PDF file

One very interesting feature of PDF files is the possibility of saving multiple plots in them just by saving them in different pages. In order to do that, you need to simply add multiple plots one after the other, as shown here:

pdf("myFile2.pdf")
ggplot(data=cont, aes(x=x, y=y, col=factor(group))) + geom_point()
ggplot(Orange, aes(age, circumference)) + geom_point(aes(colour=factor(Tree)))
dev.off()

This code will create a PDF file with two pages, each containing one of the plots. This method does not work when you manipulate the viewport manually, for instance, using the viewport() function, as shown in the previous section, since each new plot generated overwrites the previous one. So, for instance, if you want to create a PDF file containing Figure 6.1 on the first page and Figure 6.2 on the second page, the code to be run would be as follows:

pdf("myFile3.pdf")
pushViewport(viewport(layout = grid.layout(2, 2)))
print(x4, vp = viewport(layout.pos.row = 1,layout.pos.col = c(1,2)))
print(x3, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
print(x2, vp = viewport(layout.pos.row = 2, layout.pos.col = 2))

print(myScatter, vp = viewport(width = 1, height = 1, x=0.5, y = 0.5))
print(myScatterLog, vp = viewport(width = 0.4, height = 0.4, x=0.315, y = 0.76))
dev.off()

But, in this case, you will produce a PDF file containing only the last created plot. The reason for this is that grid will add the plots on top of each other. This happens in the R console when you create several plots one after the other, but only the last one is visible in the device. In order to solve the problem, you must simply specify to the grid function that the plot should be produced in a new page and not by overwriting the previous one with the grid.newpage() command. The following code will create the right PDF files with the two plots in separate pages:

pdf("myFile3.pdf")
pushViewport(viewport(layout = grid.layout(2, 2)))
print(x4, vp = viewport(layout.pos.row = 1,layout.pos.col = c(1,2)))
print(x3, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
print(x2, vp = viewport(layout.pos.row = 2, layout.pos.col = 2))

grid.newpage()

print(myScatter, vp = viewport(width = 1, height = 1, x=0.5, y = 0.5))
print(myScatterLog, vp = viewport(width = 0.4, height = 0.4, x=0.315, y = 0.76))
dev.off()

Finally, in in the pdf() function of each device function, you can also specify a number of different arguments. Here, the most important ones are width and height, which define the width and height parameters of the graphics region in inches, with a default value of 7. You can use these two parameters to modify the appearance of the graph, for instance, to modify the ratio between the two axes. You can also find additional arguments for a more precise fine-tuning of the file properties in the help pages of the individual functions.

Saving the plot after rendering it

I find creating the files using the method illustrated in the previous section very convenient and, often, this is the easiest way to save plots, but some R users do not really find the approach practical as you need to refine the properties of your plot until the desired picture is obtained and then recreate it in order to save it in a file. In this respect, it may be of interest to some R users to save the plot directly from the rendered plot in the active window of the console. In this way, as soon as you are happy with your work, you can save it directly in a file without recreating the plot. Indeed, this may be useful if you are working with very complex plots that can require time to generate. In such cases, you need not wait again for the plot to be drawn. In order to do that, you can use the following two functions with some of their arguments:

  • dev.copy(device, file)
  • ggsave(filename, width, height)

These functions are substantially similar; however, an important difference is that when using the dev.copy() function, you should specify the type of device (and the type of file to create) in the function, and then you can specify all the arguments of that device function. On the other hand, in ggsave(), you can simply specify the file extension in the filename argument, and the function will automatically select the device function needed. Also, ggsave() provides you with additional arguments to specify the file's properties.

Note

Remember that these functions with their default arguments will only save the last plot that you displayed.

You can create the myFile.pdf file of the previous example, as shown here, using the following two functions:

#### Saving a rendered plot with dev.copy()
ggplot(data=cont, aes(x=x, y=y, col=factor(group))) + geom_point()
dev.copy(pdf, file="myFile.pdf")
dev.off()

#### Saving a rendered plot with ggsave()
ggplot(data=cont, aes(x=x, y=y, col=factor(group))) + geom_point()
ggsave(file="myFile.pdf")

As illustrated, when using the dev.copy() function after all plots are saved you need to close the device using the dev.off() function. There is no such need with ggsave(), where you only need to provide the filename.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset