如何修复ggplot中的纵横比? [英] How to fix the aspect ratio in ggplot?
问题描述
我正在尝试调整绘图的大小以适合我的文档,但我很难让绘制的图表成为正方形.
I'm trying to resize a plot to fit into my document, but I'm having difficulties getting the plotted diagram do be a square.
示例:
pdf(file = "./out.pdf", width = 5, height = 5)
p <- ggplot(mydata, aes(x = col1, y = col2))
print(p)
aux <- dev.off()
尽管 x 和 y 的限制相同,但结果中的图不是方形的.我猜 R 使封闭面板为 5x5",但并不关心实际图表大小.
Although the limits for x and y are the same, the plot in the result isn't square. I guess that R makes the enclosing panel 5x5" but doesn't care about the actual diagram size.
我如何取消压缩我的图表?
推荐答案
在 ggplot
中,保持情节纵横比的机制是添加一个 coord_fixed()
图层到情节.无论实际边界框的形状如何,这都将保留绘图本身的纵横比.
In ggplot
the mechanism to preserve the aspect ratio of your plot is to add a coord_fixed()
layer to the plot. This will preserve the aspect ratio of the plot itself, regardless of the shape of the actual bounding box.
(我还建议您使用 ggsave
将结果图保存到 pdf/png/etc,而不是 pdf(); print(p); dev.off()
序列.)
(I also suggest you use ggsave
to save your resulting plot to pdf/png/etc, rather than the pdf(); print(p); dev.off()
sequence.)
library(ggplot2)
df <- data.frame(
x = runif(100, 0, 5),
y = runif(100, 0, 5))
ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed()
这篇关于如何修复ggplot中的纵横比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!