Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

r - Set the size of ggsave exactly

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...