【问题标题】:Automatic adjustment of margins in horizontal bar chart水平条形图中边距的自动调整
【发布时间】:2012-05-16 11:21:39
【问题描述】:

我需要制作一系列水平分组条形图。 barplot 函数不会自动调整绘图的边距,因此文本会被截断。

  graphics.off()      # close graphics windows
   test <- matrix(c(55,65,30, 40,70,55,75,6,49,45,34,20), 
                  nrow =3 , 
               ncol=4, 
               byrow=TRUE,
               dimnames = list(c("Subgroup 1", "Subgroup 2", "Subgroup 3"),
                               c(
                                 "Category 1 Long text",
                                 "Category 2 very Long text",
                                 "Category 3 short text",
                                 "Category 4 very short text"
                                 )))
  barplot(test, 
       las=2,
       beside = TRUE,
       legend=T,
       horiz=T)

我找不到自动将绘图向右移动的选项,就像 R dotchart 函数那样((SAS中的条形图程序也会自动调整边距)。显然,我总是可以手动调整边距使用 par 函数。

  par(mar=c(5.1, 13 ,4.1 ,2.1))

将绘图向右移动

是否可以根据文本的长度自动将绘图向右移动(即调整边距)?

我可以想到 2 个相关的方法来以编程方式执行此操作: 1)计算最长文本字符串的长度并相应调整左边距 2)为数据创建一个点图,以某种方式捕获边距并在条形图中使用相同的边距。

有没有更简单的方法? 谢谢!

【问题讨论】:

    标签: r labels margins string-length


    【解决方案1】:

    我认为您的第一个想法可能是最合适的。像这样的东西似乎工作得很好,不需要太多的东西。

    ylabels <-  c(  "1oooooooooooo",
                "2",
                "3",
                "4"
    )
    
    test <- matrix(c(55,65,30, 40,70,55,75,6,49,45,34,20), 
                      nrow =3 , 
                   ncol=4, 
                   byrow=TRUE,
                   dimnames = list(c("Subgroup 1", "Subgroup 2", "Subgroup 3"),
                                   ylabels))
    
    # adjust to the maximum of either the default 
    # or a figure based on the maximum length
    par(mar=c(5.1, max(4.1,max(nchar(ylabels))/1.8) ,4.1 ,2.1))
    
    barplot(test, 
           las=2,
           beside = TRUE,
           legend=T,
           horiz=T)
    

    在检查dotchart之后,一个更通用的解决方案也可能是使用:

    linch <-  max(strwidth(ylabels, "inch")+0.4, na.rm = TRUE)
    par(mai=c(1.02,linch,0.82,0.42))
    

    【讨论】:

    • 谢谢!我用不同的文本字符串尝试了你的代码,边距工作正常。你是怎么想出 1.8 的?
    • @MaxCherny - 只是关于 nchar:margin 比率的一些基本算术和一些试验和错误。我不能保证它会适应不同的字体大小/样式,但是如您所见,计算可以很容易地调整。
    • @thelatemail - 我想知道上面的解决方案是否考虑了扩展因素,比如我设置 cex.lab = 2,而不是默认的 1。谢谢!
    • @X.He - 上面的第二个解决方案应该 - 来自?strwidth - cex: numeric *c*haracter *ex*pansion factor; multiplied by ‘par("cex")’ yields the final character size; the default ‘NULL’ is equivalent to ‘1’.
    • @X.He - 虽然这是整个cex 声明 - 也许不是?我自己都搞糊涂了。
    猜你喜欢
    • 2017-01-19
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多