在ggplot中使用因子分割2行以上的标签

Pat*_*ckT 6 string label r ggplot2

我有一个情节,其标签是"1990-2012"形式的因素.它们太长和/或它们太多并且它们重叠.

在此输入图像描述

我想将每个标签打印成两行并在连字符后打破它,如下所示:

在此输入图像描述

对于将标签分成两部分仍然不够的情况,我还想知道如何只打印所有其他标签.

我有一个约束是标签应该"就地"完成而不预先处理data.frame和/或标签,尽管在ggplot调用中应用的自定义函数也可以.

这是神圣的数据帧(不能改变):

    df <- structure(list(Period = structure(1:13, .Label = c("0-1000", 
    "1000-1500", "1500-1700", "1700-1820", "1820-1913", "1913-1950", 
    "1950-1970", "1970-1990", "1990-2012", "2012-2030", "2030-2050", 
    "2050-2070", "2070-2100"), class = "factor"), value = c(0.000168759866884916, 
    0.000989913144738397, 0.00159894629454382, 0.0045594248070473, 
    0.00585564273031225, 0.00932876890888812, 0.0191066122563939, 
    0.0183146076484786, 0.0130117469870081, 0.00923670910453378, 
    0.00560791817163286, 0.00272731553972227, 0.00149387241891397
    ), variable = c("World", "World", "World", "World", "World", 
    "World", "World", "World", "World", "World", "World", "World", 
    "World")), .Names = c("Period", "value", "variable"), row.names = c(NA, 
    -13L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)

这是ggplot:

    library(ggplot2)
    p <- ggplot(data = df, aes(x = Period, y = value, group = variable)) + geom_line() + theme_bw() 
Run Code Online (Sandbox Code Playgroud)

如果我在连字符后面有一个空格,以下内容将起作用:

  library(stringr)
  p + scale_x_discrete(labels = function(x) str_wrap(x, width = 4))
Run Code Online (Sandbox Code Playgroud)

[上面的两行用于生成第二个图,在我手动更改数据框以在日期分隔连字符后添加空格,换句话说,在我被骗之后]

打印较少标签的以下方法通常有效,但在此处失败:

   library(scales)
   p + scale_x_discrete(breaks = pretty_breaks(n = 6)) 
Run Code Online (Sandbox Code Playgroud)

nru*_*ell 6

这是你想要的?

p + scale_x_discrete(
  labels=function(x){
    x2 <- sub("(\\d+)\\-(\\d+)",
               "\\1\\-\n\\2",
               x)
    x2
  })
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

实际上,中间体x2甚至不是必需的,这个

p + scale_x_discrete(
  labels=function(x){
    sub("(\\d+)\\-(\\d+)","\\1\\-\n\\2",x)
  })
Run Code Online (Sandbox Code Playgroud)

更紧凑一点.

编辑: 一个更简洁的解决方案,感谢@jlhoward:

p + scale_x_discrete(
  labels=function(x) sub("-","-\n",x,fixed=TRUE))
Run Code Online (Sandbox Code Playgroud)

  • 这也有效,并且避免了转义分隔符的需要,以及使用`str_wrap(...)`:`p + scale_x_discrete(labels = function(x)sub(" - "," - \n",的x,固定= TRUE))` (2认同)