[R] Wrapping long labels in barplot(2)

Marc Schwartz MSchwartz at MedAnalytics.com
Thu Apr 14 15:45:29 CEST 2005


Building on Tom's reply, the following should work:

> labels <- factor(paste("This is a long label ", 1:10))
> labels
 [1] This is a long label  1  This is a long label  2 
 [3] This is a long label  3  This is a long label  4 
 [5] This is a long label  5  This is a long label  6 
 [7] This is a long label  7  This is a long label  8 
 [9] This is a long label  9  This is a long label  10
10 Levels: This is a long label  1 ... This is a long label  9


> short.labels <- sapply(labels, function(x) paste(strwrap(x,
                         10), collapse = "\n"), USE.NAMES = FALSE)

> short.labels
 [1] "This is\na long\nlabel 1"  "This is\na long\nlabel 2" 
 [3] "This is\na long\nlabel 3"  "This is\na long\nlabel 4" 
 [5] "This is\na long\nlabel 5"  "This is\na long\nlabel 6" 
 [7] "This is\na long\nlabel 7"  "This is\na long\nlabel 8" 
 [9] "This is\na long\nlabel 9"  "This is\na long\nlabel 10"

> mp <- barplot2(1:10)
> mtext(1, text = short.labels, at = mp, line = 2)


HTH,

Marc Schwartz


On Thu, 2005-04-14 at 16:14 +0700, Jan P. Smit wrote:
> Dear Tom,
> 
> Many thanks. I think this gets me in the right direction, but 
> concatenates all levels into one long level. Any further thoughts?
> 
> Best regards,
> 
> Jan
> 
> 
> Mulholland, Tom wrote:
> > This may not be the best way but in the past I think I have done something like
> > 
> > levels(x) <- paste(strwrap(levels(x),20,prefix = ""),collapse = "\n")
> > 
> > Tom
> > 
> > 
> >>-----Original Message-----
> >>From: Jan P. Smit [mailto:janpsmit at gmail.com]
> >>Sent: Thursday, 14 April 2005 11:48 AM
> >>To: r-help at stat.math.ethz.ch
> >>Subject: [R] Wrapping long labels in barplot(2)
> >>
> >>
> >>I am using barplot, and barplot2 in the gregmisc bundle, in the 
> >>following way:
> >>
> >>barplot2(sort(xtabs(expend / 1000 ~ theme)),
> >>     col = c(mdg7, mdg8, mdg3, mdg1), horiz = T, las = 1,
> >>     xlab = "$ '000", plot.grid = T)
> >>
> >>The problem is that the values of 'theme', which is a factor, are in 
> >>some cases rather long, so that I would like to wrap/split them at a 
> >>space once they exceed, say, 20 characters. What I'm doing now is 
> >>specifying names.arg manually with '\n' where I want the 
> >>breaks, but I 
> >>would like to automate the process.
> >>
> >>I've looked for a solution using 'strwrap', but am not sure 
> >>how to apply 
> >>it in this situation.
> >>
> >>Jan Smit
> >>




More information about the R-help mailing list