[英]How to center graphs in a plot in R?
I have the following figure:我有下图:
and I´d like to have the two graphs of the third line centered.我想让第三条线的两个图表居中。 I´ve trying to get it using packages like
cowplot
and grid_arrange from ggplot2
but with no success because they change their width to fit with the width of the other two rows (like in this example),我试图使用
ggplot2
中的cowplot
和grid_arrange之类的包来获取它,但没有成功,因为它们改变了它们的宽度以适应其他两行的宽度(就像在这个例子中一样),
Is it possible to have the last two graphs centered without changing their width?是否可以在不改变宽度的情况下将最后两个图居中?
Thanks谢谢
Not the most elegant code, but it works.不是最优雅的代码,但它可以工作。 AFAIK there is a package where you can specify for each plot the size and location, but I haven't found it.
AFAIK 有一个包,您可以在其中为每个绘图指定大小和位置,但我还没有找到它。 I only used
cowplot
and function plot_grid
我只使用
cowplot
和函数plot_grid
Generating plot生成情节
x <- rnorm(100)
y <- x * 2 + rnorm(100)
plt.df <- data.frame(x, y)
p <- ggplot(plt.df, aes(x = x, y = y)) + geom_point()
Arranging them in grids将它们排列成网格
cowplot::plot_grid(
cowplot::plot_grid(p, p, p, p, p, p, ncol = 3, nrow = 2),
cowplot::plot_grid(NULL, p, p, NULL, rel_widths = c(0.5, 1, 1, 0.5), nrow = 1),
nrow = 2,
rel_heights = c(2, 1)
)
I first define a grid of 6 plots as usual.我首先像往常一样定义一个由 6 个图组成的网格。 I then define a grid of 4 plots, two of them are null, and use the
rel_widths
parameter to determine their size.然后我定义了一个由 4 个图组成的网格,其中两个为空,并使用
rel_widths
参数来确定它们的大小。 To combine all of them I again invoke plot_grid
, which accepts the two previous grids.为了结合所有这些,我再次调用
plot_grid
,它接受前两个网格。 Now define the rel_heights
parameter to make sure they are all similar in size (since there are two grids, one with twice more plots than the other, then the ratio should be 2).现在定义
rel_heights
参数以确保它们的大小都相似(因为有两个网格,一个比另一个多两倍的图,那么比率应该是 2)。
This can also be done in base R by specifying an appropriate matrix for layout
.这也可以在基础 R 中通过为
layout
指定适当的矩阵来完成。
layout.m <- matrix(c(rep(1:6, each=2),
0, rep(7:8, each=2), 0),
nrow=3, byrow=T)
This matrix specifies the locations of eight figures in a 3 × 6 grid layout with two cells left empty.此矩阵指定 3 × 6 网格布局中八个图形的位置,其中两个单元格留空。
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 1 1 2 2 3 3
# [2,] 4 4 5 5 6 6
# [3,] 0 7 7 8 8 0
Now just set the layout and do the plotting.现在只需设置布局并进行绘图。
layout(layout.m)
par(mar=c(4, 4.5, 1, .5))
x <- 1:100
for (i in 1:8) {
y <- rnorm(100)
plot(x, y)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.