15

How do I increase the grey plot area of a chart with one factor based axis and one numerical axis so that text labels in geom_text() plots are in view and do not extend outside the plot area?

ggplot showing geom_text() plot where labels extend outside the plot area

In particular, I would like to extend the grey area to provide a margin area within the plot area that allows the text labels to appear in full.

Or is there a better way?

4

1 回答 1

3

您可以使用 更改每个 ggplot 的布局选项ggplot_gtable,然后使用 显示所有绘图grid.arrange

library(ggplot2)
library(gridExtra)
## create a dummy ggplot
(g1 <- ggplot(mtcars, aes(wt, mpg)) + 
       geom_text(aes(label=rownames(mtcars)), size=6, angle=45) +
       theme(plot.margin = unit(rep(1, 4), "cm")))

显然,文本标签不会延伸到绘图区域之外。但是下面的代码只允许这样做:

gg_table <- ggplot_gtable(ggplot_build(g1))
gg_table$layout$clip[gg_table$layout$name=="panel"] <- "off"
grid.draw(gg_table)

为每个面板创建一个 gg_table,然后用于grid.arrange显示所有:

grid.arrange(gg_table, gg_table, gg_table, gg_table, ncol=2)

在此处输入图像描述

我知道这是劳动密集型的,但您可以编写一个函数来创建多个 ggplots 和 gg_tables 以节省时间。

于 2014-07-22T13:42:07.710 回答