我编写了一个函数来为包含数百个问题的大型数据集制作图表。所有图表都来自同一个数据集,并将标题作为字符串从我读过的 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
)。
关于r - 在 ggplot2 中,我可以自动将标题分成多行,而不是使用转义符\n 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33484458/