File format and exporting figures

Data Visualisation with R

Are these figures different?

Both figures used the same code below to produce the figure:

ggplot(cars, aes(speed, dist)) + geom_point()
but I saved one to a png file and the other as a svg file.

Communicating Figures

  • There are two main formats for graphics:
    • Raster formats contain description of each pixel. Common formats are:
      • jpg (or jpeg) uses a lossy data compression that results in some loss of information but usually a small file size.
      • png uses a lossless data compression and works well if the image has uniform colors.
    • Vector formats contain a geometric description and hence render smoothly at any display size. Common formats include svg, pdf and eps. E.g. svg and its source.
  • A vector format scales well to any display size, however, the file size may become prohibitively big when there are many geometric objects (i.e. displaying many data).

Exporting plots

  • To export plots made by ggplot2, use ggsave().
g <- ggplot(cars, aes(speed, dist)) + geom_point()
ggsave(filename = "myplot", 
       dev = "png",
       plot = g,
       width = 6, 
       height = 4,
       units = "in",
       dpi = 300)
  • Unfortunately you may need to adjust the font size when you check the exported plot!