3
votes

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?

1
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
That's an extremely helpful start - thanks! - MDe

1 Answers

0
votes

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