title: Proper line labelling within canvas in ggplot2
body: <h3>Problem description</h3>
  
  <p>I'm writing a function that outputs a line plot ggplot2 object. I would like to have an argument that can control whether to add labels at the end of each line. A visual example is found <a href="https://directlabels.r-forge.r-project.org/docs/lineplot/sexdeaths.last.bumpup.png" rel="nofollow noreferrer">here</a>. The difficulty lies in the variable length of line labels. Ideally, the function will be smart enough to figure out the proper extra space to expand for the labels on the right.</p>
  
  <p>In base R, there is a function <code>graphics::strwidth</code> that computes how many inches needed for the passed in string. I was wondering if there is a way that can do one step further, i.e. maps the string length to that with respect to the data scale. A dummy example is provided below for better explanation.</p>
  
  <h3>A dummy example</h3>
  
  <pre><code>library(directlabels)
  library(reshape2)
  library(ggplot2)
  dts &lt;- cbind(`my long group 1` = mdeaths, `my long group 2` = fdeaths, time = 1:length(mdeaths))
  ddf &lt;- melt(as.data.frame(dts), id = "time")
  names(ddf) &lt;- c("time", "group", "deaths")
  
  plot_wo_label &lt;- ggplot(ddf, aes(x = time, y = deaths, group = group)) + geom_line()
  plot_with_label &lt;- plot_wo_label + geom_dl(aes(label = group), method = list(dl.combine('last.points')))
  </code></pre>
  
  Plot with line label
  
  <p><a href="https://i.stack.imgur.com/sKHJw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sKHJw.png" alt="enter image description here"></a>
  As we can see above, the long line labels ('my long group 1' and 'my long group 2') get truncated due to the margin space. An ad hoc solution is to use <code>xlim</code> to expand the right edge of x-axis by trial and error. But that certainly is not an option in my case.</p>
  
  <p>I know there are posted solutions by turning off clipping (like <a href="https://stackoverflow.com/questions/29357612/plot-labels-at-ends-of-lines">here</a>), however, I imagine that some of the lines may end early and having a label at the canvas edge far away from the line end may cause difficulty to associate the labels with its corresponding lines.</p>
  
  <p>So if there is a way to figure out how much space a string of arbitrary length will occupy on the x-axis (in the dummy example, the "duration" of label "my long group 1" in the "time" axis), that would be very helpful. But this is just one possible direction in my mind, other solutions are welcome and greatly appreciated!</p>
  
  <p>Thanks!</p>