我编写了一个函数来为包含数百个问题的大型数据集绘制图形。所有图形都来自同一数据集,并将标题作为字符串从我读过的csv的“ graphtitle”列中提取。其中一些标题相当长,应分成两行。也许是因为它们来自csv,所以标题不能\n
转义,即使它们确实起作用,似乎也应该有一种比\n
在CSV适当位置添加每个变量名称更简单的方法。
有没有办法让我的函数自动分割标题行?我知道我可以更改标题的大小,但这会使它变得难以辨认
MC.Graph <- function(variable){
p <- ggplot(data = newBEPS, aes_string(x=variable)) + geom_bar(aes(y = (..count..)/sum(..count..)), width = .5)+ scale_y_continuous(labels = percent)
p <- p + ggtitle(graphwords$graphtitle[graphwords$gw.varname == variable]) +
theme(plot.title = element_text(size =20, lineheight = .5, face = "bold"))
}
以下是分解长字符串的两种方法:
gsub('(.{1,10})(\\s|$)', '\\1\n', s)
会将字符串s
分割成长度以10
分隔的行\n
。strwrap
函数与width
带paste
函数和collapse = \n
参数的参数一起使用。通过示例更容易理解...
long_title <- "This is a title that is perhaps too long to display nicely"
gsub('(.{1,10})(\\s|$)', '\\1\n', long_title)
# [1] "This is a\ntitle that\nis perhaps\ntoo long\nto display\nnicely\n"
paste(strwrap(long_title, width = 10), collapse = "\n")
# [1] "This is a\ntitle\nthat is\nperhaps\ntoo long\nto\ndisplay\nnicely"
注意:我相信strwrap
在stringi
和/或stringr
包(请参阅stringi::stri_wrap
或stringr::str_wrap
)中可以更优雅地处理(并有效地进行猜测)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句