R barplot: wrapping long text labels? R barplot: wrapping long text labels? r r

R barplot: wrapping long text labels?


There is one possible solution presented by Marc Schwartz in his post to R-help:

a <- c("I don't feel competent enough to solve problems in R", "I don't feel competent enough to solve problems in R")# Core wrapping functionwrap.it <- function(x, len){   sapply(x, function(y) paste(strwrap(y, len),                               collapse = "\n"),          USE.NAMES = FALSE)}# Call this function with a list or vectorwrap.labels <- function(x, len){  if (is.list(x))  {    lapply(x, wrap.it, len)  } else {    wrap.it(x, len)  }}

Try it:

> wrap.labels(a, 10)[1] "I don't\nfeel\ncompetent\nenough to\nsolve\nproblems\nin R"[2] "I don't\nfeel\ncompetent\nenough to\nsolve\nproblems\nin R"

or

> wrap.labels(a, 25)[1] "I don't feel competent\nenough to solve problems\nin R"[2] "I don't feel competent\nenough to solve problems\nin R"

and then create a barplot:

wr.lap <- wrap.labels(a, 10)barplot(1:2, names.arg = wr.lap, horiz = T, las = 2, cex.names = 0.5)

enter image description here


This is great; for anyone coming along here that is wondering, it also works perfectly for regular text:

plot(1:10, 1:10)txt <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit"text(8, 3.5, wrap.labels(txt, 10), cex=0.8, pos=4)

enter image description here