Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the size of ggsave exactly

Tags:

r

dpi

ggplot2

R question.

I got so confused by the width, height, dpi and unit.

Why the following two size different?

ggsave(filename = "foo.png",ggplot(mtcars, aes(x=wt, y=mpg)) +     geom_point(size=2, shape=23),width = 5, height = 4, dpi = 300, units = "in", device='png') 

and

ggsave(filename = "foo.png",ggplot(mtcars, aes(x=wt, y=mpg)) +            geom_point(size=2, shape=23),width = 5, height = 4, dpi = 72, units = "in", device='png') 

I set both of the picture's size 5 (inches) * 4 (inches). But why when I change the dpi, the size changes?

How to understand the relationship between height, width, unit and dpi?

Or how to translate these four parameters into unit of pixels, which is easier for me to understand?

like image 522
WCMC Avatar asked Jun 23 '17 00:06

WCMC


People also ask

What are the default dimensions that Ggsave ()`?

When TRUE (the default), ggsave() will not save images larger than 50x50 inches, to prevent the common error of specifying dimensions in pixels.

What is DPI in Ggsave?

The image saved on a disk is represented also as a matrix of dots. ggplot and ggsave works in physical dimension (in, cm, or mm). To go from the dimension in inches to a number of dots, ggsave uses the number of dots per inches (dpi).

How do I change the size of my Ggtitle?

To change the size of the title and subtitle, we add the theme() function to labs() or ggtitle() function, whatever you used. Here we use labs() function. Inside theme() function, we use plot. title parameter for doing changes in the title of plot and plot.

How do I save a Ggplot as PDF?

You can either print directly a ggplot into PNG/PDF files or use the convenient function ggsave() for saving a ggplot. The default of ggsave() is to export the last plot that you displayed, using the size of the current graphics device.


1 Answers

To understand why the DPI is important, consider these two plots:

ggsave(filename = "foo300.png", ggplot(mtcars, aes(x=wt, y=mpg)) +            geom_point(size=2, shape=23) + theme_bw(base_size = 10),        width = 5, height = 4, dpi = 300, units = "in", device='png') ggsave(filename = "foo150.png", ggplot(mtcars, aes(x=wt, y=mpg)) +            geom_point(size=2, shape=23) + theme_bw(base_size = 10),        width = 10, height = 8, dpi = 150, units = "in", device='png') 

The resulting files have the same pixel dimensions, but the font size in each is different. If you place them on a page with the same physical size as their ggsave() calls, the font size will be correct (i.e. 10 as in the ggsave() call). But if you put them on a page at the wrong physical size, the font size won't be 10. To maintain the same physical size and font size while increasing DPI, you have to increase the number of pixels in the image.

like image 134
Marius Avatar answered Sep 19 '22 20:09

Marius