【问题标题】:R: Increase margins between plot and axis labelsR:增加绘图和轴标签之间的边距
【发布时间】:2014-07-22 13:09:07
【问题描述】:

我正在编写代码,无法弄清楚如何影响这个间距。我尝试了 oma、mai 等,但无法缩小这个空间(绘图和轴描述“2000 年 1 月”之间的空间ETC。)。我需要哪个命令?

【问题讨论】:

  • 很难帮你。您能否添加一个可重现的示例?
  • 基础图。我不能在这里举一个例子,因为我为这些图使用了一个自定义的大 XTS 文件。
  • 请阅读如何创建minimal reproducible example

标签: r plot


【解决方案1】:

我看到您提到您尝试过 oma 和 mai,但是您尝试过 mgp 吗?您可以使用 mgp.axis.labels 改变单个轴与其刻度标签之间的间距,这需要 Hmsic package

让我们设置一个示例数据框:

require(Hmisc)
A <- rnorm(3,1,100)
B <- c("january","february","march")
dat <- data.frame(B,A)

options('mpg.axis.labels') 为您提供每个轴的默认距离 0.7

!> options('mgp.axis.labels')
 $mgp.axis.labels
 [1] 0.7 0.7

这为您提供了每个轴的 3 个值,在这种情况下,我们打印 x 轴默认值:

mgp.axis.labels(type='x')
 [1] 3.0 0.7 0.0

让我们将刻度标签和绘图之间的距离更改为原来的大约 1/3:

mgp.axis.labels(c(3.0,0.2,0.0), type='x')

plot(dat,axes=FALSE)
mgp.axis(1,at=1:3,labels=dat$B)

完成!现在 X 轴和刻度标签之间的距离更小了。

【讨论】:

    【解决方案2】:

    所以如果你有一个 xts 对象,那么你使用的是plot.xts(...)。我认为plot.xts(...) 中的默认轴边距设置不同。尝试使用mgp=... 参数(有关详细信息,请参阅?par)。

    library(xts)
    data(sample_matrix)     # sample dataset in xts package
    ts <- as.xts(sample_matrix, descr='my new xts object')
    par(mfrow=c(1,2))
    plot(ts$Open,auto.grid=F)
    plot(ts$Open,auto.grid=F,mgp=c(3,1,0))
    

    左边的图使用plot.xts(...) 的默认值,右边的图将mgp 设置为base R 中的默认值。

    【讨论】: