将长文本包装在文本框中 [英] Wrap long text in a text box

查看:78
本文介绍了将长文本包装在文本框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下可重现的系数图.

I have the following reproducible coefficient plot.

library(tidyverse)
tribble(~term, ~estimate, ~lower, ~upper, ~text,
        "a", .25, .2, .3 , "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sit amet orci vel dolor luctus auctor sed non lacus. Cras malesuada, tortor ac mattis rutrum, dui erat aliquam ipsum, id.",
        "b", -.25, -.3, -.2, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sit amet orci vel dolor luctus auctor sed non lacus. Cras malesuada, tortor ac mattis rutrum, dui erat aliquam ipsum, id.",
        "intercept",0, -.1, .1, NA) %>% 
  ggplot(aes(y = term, x = estimate, label = text)) +
  geom_point() +
  ggrepel::geom_text_repel(size = 2, label.size = 0.1) +
  geom_errorbarh(aes(xmin = lower, xmax = upper), height = 0) +
  geom_vline(aes(xintercept = 0), linetype = "dashed") +
  theme_classic()

我希望标签位于这些点的上方,并限制为较小的xlim aka宽度.有没有办法在ggplot2ggrepel中包装文本或生成某种文本框,以使此功能成为可能?

I would like the labels to be above the points and limited to a smaller xlim aka width. Is there a way to wrap text or generate some kind of text box in ggplot2 or ggrepel to make this functionality possible?

推荐答案

您可以使用此虚拟函数,该函数每隔50个字符用\n替换空格.

You can use this dummy function that replaces space with \n every 50 characters.

library(tidyverse)
data <- tribble(~term, ~estimate, ~lower, ~upper, ~text,
        "a", .25, .2, .3 , "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sit amet orci vel dolor luctus auctor sed non lacus. Cras malesuada, tortor ac mattis rutrum, dui erat aliquam ipsum, id.",
        "b", -.25, -.3, -.2, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sit amet orci vel dolor luctus auctor sed non lacus. Cras malesuada, tortor ac mattis rutrum, dui erat aliquam ipsum, id.",
        "intercept",0, -.1, .1, "Lorem impsum")

data$textBreaks <- sapply(strsplit(data$text, " "), function(x) {
    spacePosition <- cumsum(nchar(x))
    placeBreak <- spacePosition[which(diff(spacePosition %/% 50) == 1)] + 1
    result <- paste(x, collapse = " ")
    for(i in placeBreak) {
        substring(result, i, i) <- "\n"
    }
    result
})
ggplot(data, aes(estimate, term,label = textBreaks)) +
    geom_point() +
    ggrepel::geom_text_repel(size = 2) +
    geom_errorbarh(aes(xmin = lower, xmax = upper), height = 0) +
    geom_vline(aes(xintercept = 0), linetype = "dashed") +
    theme_classic()

PS:如果只有一个长字(> 50个字符),则将无法使用.

PS.: It won't work if there's only one long word (> 50 characters).

这篇关于将长文本包装在文本框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆