R barplot: packaging long text labels?

I mean this question ( Automatic adjustment of fields in a horizontal histogram ). I would ask my question right there, but it seems that I do not have permission yet.

Imagine a horizontal diagram (for example, in a related question) where you can have extreme long lines, as we always have in the social sciences (for example, wording a question in the form of a poll like β€œI don’t feel competent enough to solve problems in R” )

Thelatemail user gave a decision on how to move the beginning of the graph depending on the length of the text labels. This works fine for labels with a length of 10 to 15 characters, but if you need to label your Y axis with very long labels, you cannot move the beginning of the graph endlessly.

Thus, it is more advisable to wrap text labels after a special number of words / characters, for example, in my example, you can wrap it as follows:

"I don't feel competent enough to solve problems in R" 

However, I do not know how to wrap text labels in R and, moreover, how to take into account the wrapping to automatically move the beginning of the plot. For example, if I have a label of 50 characters, and I transfer it to two lines of 25 characters, then it would be great if this solution was taken into account when solving thelatemail .

I recommend any help in solving this problem! Thanks!

+6
source share
2 answers

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

 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 function wrap.it <- function(x, len) { sapply(x, function(y) paste(strwrap(y, len), collapse = "\n"), USE.NAMES = FALSE) } # Call this function with a list or vector wrap.labels <- function(x, len) { if (is.list(x)) { lapply(x, wrap.it, len) } else { wrap.it(x, len) } } 

Try:

 > 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 barcode:

 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

+7
source

It's great; for those coming here, which is interesting, it also works great for plain 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

0
source

Source: https://habr.com/ru/post/958919/


All Articles