Exporting Pretty Graphics

Making nice graphics with R!

While R does come with some very nice built in graphics capabilities, many of which create production quality graphics out of the box, it takes some effort to produce the exact image you want. The first thing you might notice when trying to produce graphics is that the bitmap images R creates are incredibly grainy when printed to their own file. Unfortunately you’re almost always going to need a bitmap image (png, jpg, gif) to work with in practice. So how to improve the quality of the images?

The vector graphics (svg) are much better. The lines are smooth and they can be resized as you like.

Here’s how I create the images for this blog:

svg(“filename.svg”, width=7, height=7)
# plotting commands go here
dev.off()

This produces a square svg file, 7 inches by 7 inches.

In the program Inkscape, which is free online, turning it into a bitmap is just a matter of going to File → Export Bitmap, setting the dpi to something reasonable (like 200 or 300) and clicking Export.

Just like that you have a very nice image to use however you want. Storing it as an svg file also makes it convenient to edit and resize without loss of quality later. That’s the whole reason vector graphics exist!

It is possible to write code that produces a nicely size png file directly but unfortunately the results are not impressive.

png(“filename.png”, width=1400, height=1400)
# plotting commands go here
dev.off()

Let’s compare two versions of some data from the faithful data.

testcompareimg

The file that started life as an svg is much easier to read and looks a lot more like what I intended to create. Saving the files in one format and then converting them to another may seem fiddly but trying to make R print bitmaps that look nice requires a lot more tinkering. The best way to make sure that what you see is what you get is by using svg files.

Leave a comment