如何在ggplot2中指定图形大小而与轴标签无关 [英] How to specify the size of a graph in ggplot2 independent of axis labels

查看:203
本文介绍了如何在ggplot2中指定图形大小而与轴标签无关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数据框并想要绘制一个图

Say I have a data frame and want to make a plot

df <- melt(iris)

p <- ggplot(data = df, aes(x = Species, y = value)) + 
       geom_boxplot() + theme(aspect.ratio = 1)

然后我想使用ggsave()保存该图的pdf

I then want to use ggsave() to save a pdf of this plot

ggsave(plot = p, width = 3, height = 3, dpi = 300, filename = "not squished axis.pdf")

问题是我想指定图本身的尺寸,但与轴标签无关,以便下面指定的图在轴的绝对长度方面具有相同的大小和尺寸。

The problem is that I want to specify the dimensions of the plot itself but independently of the axis labels so that the plot specified below will have the same size and dimensions in terms of the absolute length of the axes.

q <- ggplot(data = df, aes(x = Species, y = (value)*10000000)) +
       geom_boxplot() + theme(aspect.ratio = 1)

ggsave(plot = q, width = 3, height = 3, dpi = 300, filename = "squished axis.pdf")

是否可以轻松地做到这一点?

Is there a way to do this easily?

以下是一个在轴长方面更接近我想要的图的示例:

Here is an example of a plot closer to what I would like in terms of the axis lengths:

唯一的问题是,通过更改宽高比,我最终会挤压y轴以使x轴更接近偶数长度...

the only problem is that by changing the aspect ratio, I end up squishing the y axis to make the x axis closer to even in length...

推荐答案

使用 ggplotGrob 。像这样的东西:

g1 <- ggplot(...)
g2 <- ggplot(...)

g1grob <- ggplotGrob(g1)
g2grob <- ggplotGrob(g2)

grid.arrange(g1grob, g2grob)

这篇关于如何在ggplot2中指定图形大小而与轴标签无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆