自动调整水平条形图中的边距

Max*_*x C 11 r margins labels string-length

我需要制作一系列水平分组条形图.条形图功能不会自动调整绘图的边距,因此文本会被切断.

  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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我找不到一个选项来自动向右移动图,R点图功能的方式((SAS中的条形图程序也会自动调整边距).显然,我总是可以使用par函数手动调整边距.

  par(mar=c(5.1, 13 ,4.1 ,2.1))
Run Code Online (Sandbox Code Playgroud)

将剧情向右移动

在此输入图像描述

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

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

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

the*_*ail 11

我认为你的第一个想法可能是最合适的.这样的东西似乎工作正常,并且需要的东西不多.

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)
Run Code Online (Sandbox Code Playgroud)

检查后dotchart,还可以使用更通用的解决方案:

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