增加ggplot2中axis.title和axis.text之间的空间(版本> = 0.9.0)

时间:2012-02-03 16:24:47

标签: r ggplot2

我目前正在使用github的最新版ggplot2。

在版本0.8.9中,我可以执行以下操作来增加axis.title和axis.text之间的空间:

在:

ggplot(diamonds, aes(clarity)) + geom_bar() + opts(
    axis.title.x = theme_text(vjust=-1.1)
)

修正:

ggplot(diamonds, aes(clarity)) + geom_bar() + opts(
    axis.title.x = theme_text(vjust=-1.1),
    plot.margin = unit(c(1, 1, 0.8, 0.5), "lines")
)

link to graph

并且axis.title变得完全可见。

在最新的github版ggplot2中,plot.margin对axis.title没有影响:

ggplot(diamonds, aes(clarity)) + geom_bar() + opts(
    axis.title.x = theme_text(vjust=-0.2),
    plot.margin = unit(c(1, 1, 2, 0.5), "lines"))

link to graph

(注意增加的底部边距 - 我无法让plot.background在最新的开发版本中工作)

似乎0.8.9允许axis.title在plot.margin创建的额外空间上移动,但在最新的开发版本中不允许这样做。

在最新的开发版本中是否有新方法可以完成此任务(或快速修复)?

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:9)

如何正确地进行

margin中使用element_text axis.title属性theme。 我对x和y使用不同的边距,因为我将y标题旋转到水平(使其更容易阅读)。

library(ggplot2)
library(gridExtra)

ggplot(diamonds, aes(clarity)) +
    geom_bar() +
    theme(
        axis.title.x = element_text(margin = unit(c(3, 0, 0, 0), "mm")),
        axis.title.y = element_text(margin = unit(c(0, 3, 0, 0), "mm"), angle = 0)
    )

Demo of axis title margin

老黑客

ggplot不再支持

optstheme_text。因此,我的快速而肮脏的解决方案是在标题的开头或结尾添加换行符。它可能很丑,但只需很少的努力即可完成工作。

ggplot(diamonds, aes(clarity)) +
    geom_bar() +
    xlab("\nClarity") + ylab("Count\n")

答案 1 :(得分:7)

我正在结束这个问题,因为我现在提出的解决办法似乎暂时搁置(见下文)。

我在plot-render.r中找到了以下代码:64:

xlab_height <- grobHeight(xlabel) + 
  if (is.null(labels$x)) unit(0, "lines") else unit(0.5, "lines")
plot_table <- gtable_add_rows(plot_table, xlab_height)
plot_table <- gtable_add_grob(plot_table, xlabel, name = "xlab", 
  l = panel_dim$l, r = panel_dim$r, t = -1)

ylab_width <- grobWidth(ylabel) + 
  if (is.null(labels$y)) unit(0, "lines") else unit(0.5, "lines")
plot_table <- gtable_add_cols(plot_table, ylab_width, pos = 0)
plot_table <- gtable_add_grob(plot_table, ylabel, name = "ylab",
  l = 1, b = panel_dim$b, t = panel_dim$t)

我改为:

xlab_height <- grobHeight(xlabel) + 
  if (is.null(labels$x)) unit(0, "lines") else unit(0.5, "lines")
plot_table <- gtable_add_rows(plot_table, xlab_height)
plot_table <- gtable_add_grob(plot_table, xlabel, name = "xlab", 
  l = panel_dim$l, r = panel_dim$r, t = -1, clip = "off") <---- here

ylab_width <- grobWidth(ylabel) + 
  if (is.null(labels$y)) unit(0, "lines") else unit(0.5, "lines")
plot_table <- gtable_add_cols(plot_table, ylab_width, pos = 0)
plot_table <- gtable_add_grob(plot_table, ylabel, name = "ylab",
  l = 1, b = panel_dim$b, t = panel_dim$t, clip = "off") <---- here

这允许人们使用hjust / vjust结合plot.margin移动axis.titles而不剪辑。

根据要求,我在github填写了这个错误。