3
votes

I'm using ggplot2 with the directlabels package in a geom_line() plot, and I would like one of the labels to read "X-M". However, in my data.frame() "X-M" as column name gets renamed to "X.M", and I couldn't find documentation on how to provide the direct.label function with custom labels names, nor reading the source helped. (directabels doesn't seem to honor the label names set in the ggplot scale, which is the first thing that I tried.)

Sample code:

library("scales")
library("reshape2")
library("ggplot2")
library("directlabels")

data = data.frame(
  C = c(1.2, 1.4, 0.3, -2.0, 0.5),
  I = c(1.2, 1.5, -1.3, -3.8, 1.8),
  G = c(0.2, 0.3, 0.3, 0.2, 0.2),
  "X-M" = c(2.9, -0.7, 0.3, -2.8, 1.5) +
          c(-2.7, 0.2, 0.4, 3.6, -2.4),
  year = c("2006", "2007", "2008", "2009", "2010"))

p <- ggplot(data = melt(data), aes(year, value, color = variable)) +
  geom_line(aes(group = variable)) +
  scale_color_hue(breaks = c("C", "I", "G", "X.M"),
                  labels = c("C", "I", "G", "X-M"))  # directlabels doesn't
                                                     # use this

# Compare:
p

# with:
direct.label(p, list(last.points, hjust = -0.25))

Resulting graphs can be seen here. The one with directlabels uses "X.M" instead of "X-M". Many thanks in advance!

1
+1 for reproducible example. Welcome to SO.Andrie

1 Answers

3
votes

The package directlabels seems to get the labels from the column names in your data.

This means you have to make sure your labels are correct in the data to start with. To do this, you have to set check.names=FALSE when you create the data.frame:

data = data.frame(
  C = c(1.2, 1.4, 0.3, -2.0, 0.5),
  I = c(1.2, 1.5, -1.3, -3.8, 1.8),
  G = c(0.2, 0.3, 0.3, 0.2, 0.2),
  "X-M" = c(2.9, -0.7, 0.3, -2.8, 1.5) +
    c(-2.7, 0.2, 0.4, 3.6, -2.4),
  year = c("2006", "2007", "2008", "2009", "2010"),
  check.names=FALSE)

data
     C    I   G  X-M year
1  1.2  1.2 0.2  0.2 2006
2  1.4  1.5 0.3 -0.5 2007
3  0.3 -1.3 0.3  0.7 2008
4 -2.0 -3.8 0.2  0.8 2009
5  0.5  1.8 0.2 -0.9 2010

Now plot:

p <- ggplot(data = melt(data), aes(year, value, color = variable)) +
  geom_line(aes(group = variable)) 
direct.label(p, list(last.points, hjust = -0.25))

enter image description here