ggplot2对齐两个刻面图的顶部

时间:2016-12-09 03:59:20

标签: r ggplot2 gridextra r-grid

我需要安排两个分面图,如下:

d = data.frame(Index = LETTERS[1:5],x=1:5,y=1:5)
A = ggplot(subset(d,Index == 'A'),aes(x,y)) + 
  theme_bw() + 
  theme(axis.title.x = element_blank()) + 
  geom_point() + facet_wrap(~Index) + labs(title = "Title, The Title", 
                                           subtitle = "Subtitle, The Subtitle",
                                           y = "Side Axes")
B = ggplot(subset(d,Index != 'A'),aes(x,y)) +
  theme_bw() + 
  theme(axis.title.x = element_blank(), axis.title.y = element_blank()) + 
  geom_point() + facet_wrap(~Index) + labs(title = "", subtitle = "")
g = gridExtra::arrangeGrob(A,B,ncol=2,bottom="Bottom Axes")
grid.arrange(g)

产生以下内容:

Output

从上面可以看出,绘图区域的顶部边缘之间存在轻微的不对齐。这是由“逗号”引起的。在标题和副标题中。

有谁知道如何强制对齐顶边?我需要左侧情节的标题和副标题,右侧有一个(空)标题,副标题。

3 个答案:

答案 0 :(得分:4)

@ CephBirk的解决方案是一个聪明而简单的方法。对于像这样的黑客行为不起作用的情况,您可以从图中删除标题和子标题,然后使用grid.arrange和{为您创建单独的grob,以及图表。 {1}}。在下面的代码中,我还添加了一个arrangeGrob作为图nullGrob()A之间的间隔符,以便左边的右x标签(B)图表没有被切断。

1.50

enter image description here

答案 1 :(得分:2)

这有点像hackish,但你可以在左边有相同的标题和副标题,但是用白色字体打印。 :)你说这是由于逗号,所以修复它。

不是最满意的,但它完成了工作。

In [112]: s
Out[112]:

a    0
b    1
c    2
dtype: int64

In [113]: d = s.apply(lambda x: pd.DataFrame([[x,x*2],[x*3,x*4]]).stack()).stack().stack()

In [114]: d
Out[114]:

a  0  0    0
      1    0
   1  0    0
      1    0
b  0  0    1
      1    3
   1  0    2
      1    4
c  0  0    2
      1    6
   1  0    4
      1    8
dtype: int64

答案 2 :(得分:2)

egg::ggarrange(A, B, ncol=2, bottom="Bottom Axes")

enter image description here

相关问题