左对齐两个图形边缘(ggplot) [英] left align two graph edges (ggplot)

查看:234
本文介绍了左对齐两个图形边缘(ggplot)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ggplot,并有两个图表,我想在彼此之上显示。我使用gridExtra中的 grid.arrange 来堆叠它们。问题是我希望图形的左边缘与右边缘对齐,而不管轴标签如何。 (问题出现是因为一张图的标签很短,而另一张图的标签很长)。



问题:

我该怎么做?我没有嫁给grid.arrange,但ggplot2是必须的。



我试过的是:

我试过用宽度和高度以及ncol和nrow来制作一个2×2的网格,并将视觉对象放置在对角,然后播放宽度,但我无法获得对角的视觉效果。

  require(ggplot2); require(gridExtra)
A <-ggplot(CO 2,aes(x = Plant))+ geom_bar()+ coord_flip()
B < - ggplot CO2,aes(x = Type))+ geom_bar()+ coord_flip()
grid.arrange(A,B,ncol = 1)


试试这个,

  gA < -  ggplotGrob(

A)
gB < - ggplotGrob(B)
maxWidth = grid :: unit.pmax(gA $ widths [2:5],gB $ widths [2:5])
gA $ widths [2:5]< - as.list(maxWidth)
gB $ widths [2:5]< - as.list(maxWidth)
grid.arrange(gA,gB,ncol = 1)

编辑

以下是一个更通用的解决方案(适用于任意数量的地块),包括使用 rbind.gtable 的修改版本in gridExtra

  gA < -  ggplotGrob(A)$ b $ (gB,gB))


I'm using ggplot and have two graphs that I want to display on top of each other. I used grid.arrange from gridExtra to stack them. The problem is I want the left edges of the graphs to align as well as the right edges regardless of axis labels. (the problem arises because the labels of one graph are short while the other is long).

The Question:
How can I do this? I am not married to grid.arrange but the ggplot2 is a must.

What I've tried:
I tried playing with widths and heights as well as ncol and nrow to make a 2 x 2 grid and place the visuals in opposite corners and then play with the widths but I couldn't get the visuals in opposite corners.

require(ggplot2);require(gridExtra)
A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +coord_flip() 
B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip() 
grid.arrange(A, B, ncol=1)

解决方案

Try this,

 gA <- ggplotGrob(A)
 gB <- ggplotGrob(B)
 maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
 gA$widths[2:5] <- as.list(maxWidth)
 gB$widths[2:5] <- as.list(maxWidth)
 grid.arrange(gA, gB, ncol=1)

Edit

Here's a more general solution (works with any number of plots) using a modified version of rbind.gtable included in gridExtra

gA <- ggplotGrob(A)
gB <- ggplotGrob(B)
grid::grid.newpage()
grid::grid.draw(rbind(gA, gB))

这篇关于左对齐两个图形边缘(ggplot)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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