简体   繁体   English

R ggplot-使用ggsave设置图例/轴尺寸

[英]R ggplot - set legend/axis sizes with ggsave

so I have df like this 所以我有这样的DF

df <- read.table(text="
   amount      nr      date
   50          1       2017-01-01
   150         1       2017-01-03
   1500        2       2017-01-04
   1450        2       2017-01-04
   1250        2       2017-01-04
   950         1       2017-02-05
   120         3       2017-02-06
   300         3       2017-04-06
", header=TRUE)

I created an plot from this df 我从这个df创建了一个情节

ggplot(test, aes(x = date, y = amount, fill = nr, group = 1)) +
  geom_bar(stat = "identity")

Everything works well until I save this plot with code below 一切正常,直到我用下面的代码保存此图

ggsave(filename="D:/Documents/units_plot.png", width = 4, height = 2)

I can't figure out how should I properly set image dimensions (it should be 1000x500px) and how to set text size for legends, axes text sizes. 我不知道如何正确设置图像尺寸(应为1000x500px)以及如何设置图例的文字大小,坐标轴文字大小。 Usually I do it by theme() option i ggplot but for some reason legend is so huge in exported file. 通常我通过ggplot中的theme()选项来执行此操作,但是由于某些原因,图例在导出的文件中是如此之大。

ggplot bases its size calculations around the physical size of the image once it's printed. ggplot的尺寸计算基于图像打印后的物理尺寸。 To get a certain pixel size, you need to pick a good value for DPI (number of pixels per inch), and use that to calculate the size: 要获得一定的像素大小,您需要为DPI(每英寸的像素数)选择一个合适的值,然后使用该值计算大小:

ggplot(test, aes(x = date, y = amount, fill = nr, group = 1)) +
    geom_bar(stat = "identity") +
    theme_grey(base_size = 12)

dpi = 96
ggsave(filename="units_plot.png", width = 1000 / dpi, height = 500 / dpi,
       dpi = dpi)

If you pick different DPI values, you'll have to test which font sizes work with that DPI, without making the labels too big or small - I don't think there's any way around that. 如果您选择不同的DPI值,则必须测试哪种字体大小适用于该DPI,而不能使标签太大或太小-我认为这没有任何解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM