3

I'm trying to vary the size of a geom_text() layer in a ggplot so that the labels are always narrower than a given range. The ranges are defined in the data, but what I don't know is how to scale the label to be narrower than that, without a ton of trial and error.

What I hope is that I can construct a function of label size and nchar(label) (realizing character width varies a bit) that would return a width that I could compare to the shape width, and scale down until no longer necessary.

Are the ggplot label sizes defined as a number of pixels, percentage of the plot height, or something else like that?

Jaap
  • 81,064
  • 34
  • 182
  • 193
MDe
  • 2,478
  • 3
  • 22
  • 27
  • 3
    Rather than `nchar(label)` you may want to use `strwidth(label)`. I only found `strwidth()` as I finished my last project on which it would have been very useful. – Gregor Thomas Mar 27 '14 at 18:30
  • That's an extremely helpful start - thanks! – MDe Mar 27 '14 at 18:40

1 Answers1

0

would this be a helpful place to start? (if not please feel free to delete my post). You add your ranges to ranges = rnorm(foo, 5, 1).

library(ggplot2)
library(directlabels)

set.seed(67)
foo <- 8
df <- data.frame(x = rnorm(foo, 1, .5), y=rnorm(foo, 1, .5), ranges = rnorm(foo, 5, 1), let=letters[1:foo])

p <- ggplot(df, aes(x, y, color=let)) + geom_point()  + scale_colour_brewer(palette=5)
direct.label(p, 
    list("top.points", rot=0, cex=df[,3], 
          fontface="bold", fontfamily="serif", alpha=0.8))          

s

Eric Fail
  • 8,191
  • 8
  • 72
  • 128