如何在R中包装标签文本?

时间:2019-03-25 13:44:11

标签: r

我正在使用带有调查数据的水平条形图。 y轴的标签将是调查中的问题。这些问题很长,因此我需要包装每个问题的文本,使其出现在2-3行上。有人可以分享在base R中最简单的方法吗?

counts <- c(5, 4.9, 4.4, 4.8, 4.9, 5.0, 4.9, 4.9, 4.9)

barplot(counts, col=c("deepskyblue2"), border = NA,  
        family="Arial", horiz = T, xlim = range(0,6))

我需要每个标签都可以跨越2-3行。

1 个答案:

答案 0 :(得分:4)

这是一个非常原始的解决方案,并不完全基于R:

counts <- c(5, 4.9, 4.4, 4.8, 4.9, 5.0, 4.9, 4.9, 4.9)
library(stringr) # for the function str_wrap()
library(magrittr) # just for the pipe %>%, not strictly necessary
names(counts) <- c(
  "I'm working on a horizontal",
  "barplot with survey data.",
  "The labels for the y axis",
  "will be questions from the survey.",
  "The questions are rather long, and",
  "therefore I need to wrap the text",
  "of each question so that it appears",
  "on 2-3 lines. Can someone share",
  "how to most simply do this in base R?") %>% str_wrap(width = 20)

par(mai=c(1,2,1,1)) # make space for the label
barplot(counts, col=c("deepskyblue2"), border = NA, family="Arial", horiz = T, xlim = range(0,6), las = 2)

enter image description here

PS。如果基数R是严格要求,则您应该可以编写类似于str_wrap()的代码。

编辑

您可以基于基数R中的strwrap()定义自己的函数,并删除stringr依赖项:

our_strwrap <- function(x) lapply(strwrap(x, width = 20, simplify= FALSE), paste, collapse = "\n")