r - 在 ggplot2 中,我可以自动将标题分成多行,而不是使用转义符\n 吗?

标签 r ggplot2

我编写了一个函数来为包含数百个问题的大型数据集制作图表。所有图表都来自同一个数据集,并将标题作为字符串从我读过的 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函数带有 widthpaste 包裹的参数功能和 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"
    

    注意我相信 strwrapstringi 中处理得更优雅(并且猜测更有效)和/或 stringr包(见 stringi::stri_wrapstringr::str_wrap )。

    关于r - 在 ggplot2 中,我可以自动将标题分成多行,而不是使用转义符\n 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33484458/

    相关文章:

    每周数据的 R 时间序列绘图

    r - 增加线图中线的最大宽度

    r - ggplot2 的facet_grid 内部元素中具有多个重复值的不同重新排序

    r - 使用 "scale_y_continuous(trans = ' 反向时无法在 ggplot 中使用 ylimit')"

    r - 具有新默认颜色的 ggplot2 几何图形

    r - [ :alpha:] class and [a-zA-Z]; Is [:alpha:] OS independent? 之间的差异

    r - 长数据 - 当每个人的第一个值 =X R 时删除所有行

    R: 如何使用 ggplot2 将数据表绘制成特定的顺序?

    r - 使用 tryCatch 保存引发警告的对象

    r - 如何格式化ggplot2图例的数值?