水平条形图中边距的自动调整 [英] Automatic adjustment of margins in horizontal bar chart
问题描述
我需要制作一系列水平分组条形图.barplot 函数不会自动调整绘图的边距,因此文本会被截断.
I need to produce a series of horizontal grouped bar charts. The barplot function does not automatically adjust the margins of the plot, therefore the text gets cut off.
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 函数.
I can't find an option to automatically move the plot further to the right, the way R dotchart function does it ( (barchart procedure in SAS adjusts the margins automatically as well). Obviously, I can always adjust the margins manually using par function.
par(mar=c(5.1, 13 ,4.1 ,2.1))
将绘图向右移动
是否可以根据文本的长度自动将绘图向右移动(即调整边距)?
Is there an option to move the plot to the right (i.e. adjust the margins) automatically depending on the length of the text?
我可以想到 2 个相关的方法来以编程方式执行此操作:1)计算最长文本字符串的长度并相应调整左边距2)为数据创建一个点图,以某种方式捕获边距并在条形图中使用相同的边距.
I can think of 2 related appproaches to do it programmatically: 1) Calculate the length of the longest text string and accordingly adjust the left margin 2) Create a dotchart plot for the data, somehow capture the margins and use the same margins in bar chart.
有没有更简单的方法?谢谢!
Is there an easier way to do it? Thanks!
推荐答案
我认为你的第一个想法可能是最合适的.像这样的东西似乎工作得很好,不需要太多的东西.
I think your first idea is probably the most appropriate. Something like this seems to work okay and requires not much stuffing about.
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
后,也可以使用更通用的解决方案:
After inspecting dotchart
, a more generalisable solution may also be to use:
linch <- max(strwidth(ylabels, "inch")+0.4, na.rm = TRUE)
par(mai=c(1.02,linch,0.82,0.42))
这篇关于水平条形图中边距的自动调整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!