将长文本类别包裹在 ggplot 轴上

问题描述 投票:0回答:2

我想在 R 中的 ggplot 上包装长类别标签。我知道我可以使用 str_wrap() 和 scale_x_manual() 将它们包装到新行上,说 10 个单词。然而,我的几个类别标签是连续字符的主字符串,没有空格(例如,它们有下划线而不是空格)。我怎样才能在 40 个字符之后换行?

这是一个例子

df = data.frame(x = c("label", "long label with spaces", "long_label_with_no_spaces_in_it_which_is_too_lon"), 
                y = c(10, 15, 20))

ggplot(df, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10))
r ggplot2 stringr
2个回答
0
投票

将下划线转换为空格,然后

str_wrap
,然后用下划线替换空格:

ggplot(df, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = ~ gsub(' ', '_', str_wrap(gsub('_', ' ', .x), 40)))

虽然说实话,我觉得不去替换下划线看起来更专业:

ggplot(df, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = ~ str_wrap(gsub('_', ' ', .x), 20))


0
投票

如果所有示例都如您所述,我将添加代码,将下划线更改为空格。

df = data.frame(x = c("label", "long label with spaces", "long_label_with_no_spaces_in_it_which_is_too_lon"), 
            y = c(10, 15, 20))

df$x <- gsub("_","",df$x)

ggplot(df, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10))

如果您确实想在 10 个字符后添加换行符,也许此代码可以工作:

df$x<- insert_line_breaks(df$x, width = 10)
© www.soinside.com 2019 - 2024. All rights reserved.