gpt4 book ai didi

r - 使用因子将 ggplot 中的标签拆分为 2 行

转载 作者:行者123 更新时间:2023-12-04 11:32:19 25 4
gpt4 key购买 nike

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

enter image description here

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

enter image description here

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

我的一个限制是标签应该在没有预处理 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")

这是ggplot:
    library(ggplot2)
p <- ggplot(data = df, aes(x = Period, y = value, group = variable)) + geom_line() + theme_bw()

如果我在连字符后面有一个空格,以下将起作用:
  library(stringr)
p + scale_x_discrete(labels = function(x) str_wrap(x, width = 4))

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

以下打印较少标签的方法通常有效,但在此处失败:
   library(scales)
p + scale_x_discrete(breaks = pretty_breaks(n = 6))

最佳答案

这是你想要的?

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

enter image description here

其实中间 x2甚至没有必要,这个
p + scale_x_discrete(
labels=function(x){
sub("(\\d+)\\-(\\d+)","\\1\\-\n\\2",x)
})

更紧凑一点。

编辑:
更简洁的解决方案,感谢@jlhoward:
p + scale_x_discrete(
labels=function(x) sub("-","-\n",x,fixed=TRUE))

关于r - 使用因子将 ggplot 中的标签拆分为 2 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27473772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com