对齐ggplot中的绘图区域 [英] Align plot areas in ggplot

查看:24
本文介绍了对齐ggplot中的绘图区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 grid.arrange 在 ggplot 生成的同一页面上显示多个图形.这些图使用相同的 x 数据,但具有不同的 y 变量.由于 y 数据具有不同的尺度,这些图具有不同的维度.

I am trying to use grid.arrange to display multiple graphs on the same page generated by ggplot. The plots use the same x data but with different y variables. The plots come out with differing dimensions due to the y-data having different scales.

我尝试在 ggplot2 中使用各种主题选项来更改绘图大小并移动 y 轴标签,但没有一个可以对齐绘图.我希望将图排列在 2 x 2 的正方形中,以便每个图的大小相同并且 x 轴对齐.

I have tried using various theme options within ggplot2 to change the plot size and move the y axis label but none have worked to align the plots. I want the plots arranged in a 2 x 2 square so that each plot is the same size and the x-axes align.

这里是一些测试数据:

A <- c(1,5,6,7,9)
B <- c(10,56,64,86,98)
C <- c(2001,3333,5678,4345,5345)
D <- c(13446,20336,24333,34345,42345)
L <- c(20,34,45,55,67)
M <- data.frame(L, A, B, C, D)

以及我用来绘制的代码:

And the code that I am using to plot:

x1 <- ggplot(M, aes(L, A,xmin=10,ymin=0)) + geom_point() + stat_smooth(method='lm')
x2 <- ggplot(M, aes(L, B,xmin=10,ymin=0)) + geom_point() + stat_smooth(method='lm')
x3 <- ggplot(M, aes(L, C,xmin=10,ymin=0)) + geom_point() + stat_smooth(method='lm')
x4 <- ggplot(M, aes(L, D,xmin=10,ymin=0)) + geom_point() + stat_smooth(method='lm')
grid.arrange(x1,x2,x3,x4,nrow=2)

如果您运行此代码,您将看到底部的两个图由于 y 轴单位的长度较长而具有较小的绘图区域.

If you run this code, you will see that the bottom two plots have a smaller plot area due to the greater length of the y-axes units.

如何使实际绘图窗口相同?

How do I make the actual plot windows the same?

推荐答案

我会使用 faceting 来解决这个问题:

I would use faceting for this problem:

library(reshape2)
dat <- melt(M,"L") # When in doubt, melt!

ggplot(dat, aes(L,value)) + 
geom_point() + 
stat_smooth(method="lm") + 
facet_wrap(~variable,ncol=2,scales="free")

注意:外行可能会错过刻面之间的尺度不同.

Note: The layman may miss that the scales are different between facets.

这篇关于对齐ggplot中的绘图区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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