ggplot:减少为y轴文本保留的空间

时间:2014-04-27 14:02:49

标签: r ggplot2 gtable

我有以下双重图(来自another SO question):

dual plot

以下是生成图表的代码:

library(ggplot2)
library(gtable)

df <- data.frame(x=c(5,2,7,3),
    y=c("asdasxfqwe","a","b","c"),
    facet=c(1,1,2,2))

# First plot (a bit of extra space between facets)
p <- ggplot(df, aes(x, y)) + facet_grid(~facet) + 
        geom_point() + 
        theme(panel.margin = unit(4, "lines"),
              axis.text.y  = element_text( hjust=0.5))

# get y-axis labels 
g <- ggplotGrob(p)
axis <- gtable_filter(g, "axis-l")[["grobs"]][[1]][["children"]][["axis"]][,1]

# remove axis
g[["grobs"]][[4]][["children"]][["axis"]] <- NULL

# build plot & add axis to LHS of left facet
panels <- subset(g$layout, name == "panel")
g <- gtable_add_grob(g, grobs=axis, t = unique(panels$t),
    l=tail(panels$l, -1)-1)

grid.newpage()
grid.draw(g)

据我所知,左侧的空白区域是y轴文本在使用gtable代码移动之前所用的位置。如何摆脱这个空旷的空间?

1 个答案:

答案 0 :(得分:4)

升级评论:

由于您正在编辑gtable,因此可以将相关宽度设置为较小的值,

 g[["widths"]][3] <- list(unit(1, "line"))