如何解决ggplot的纵横比问题? [英] How to fix the aspect ratio in ggplot?

查看:349
本文介绍了如何解决ggplot的纵横比问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调整一个情节以适应我的文档,但是我很难让绘制的图表成为正方形。



示例: / b>

  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但不关心实际的图表大小。



我怎样才能取消我的图表? 就是在图上添加一个 coord_fixed()图层,不管实际边界框的形状如何,这将保留图的自身宽高比。



(我还建议您使用 ggsave 将结果图保存为pdf / png / etc,而不是<$ c $

 库(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()


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.

Example:

pdf(file = "./out.pdf", width = 5, height = 5)
p <- ggplot(mydata, aes(x = col1, y = col2))
print(p)
aux <- dev.off()

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.

How can I unsquash my diagrams?

解决方案

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.

(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屋!

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