How can you use directlabels and ggplot2?
Asked Answered
D

1

9

I'm trying use the directlabels package to label two lines I have in a simple plot (I'm using ggplot2)

enter image description here

My code is as follows:

# libraries
library(ggplot2)
library(directlabels)

# Variables
A = array(1000,100)
F = seq(length=100, from=0, by=10)
f = array(5,100)

# make data frame 1
df <- data.frame(X = F * f/A, Y = F/A)

# plot line 1
p = ggplot(df, aes(x=X,y=Y)) 
p = p + geom_line(colour="#56B4E9") 

# make data frame 2
df1 <- data.frame(X = F * f * 2/A, Y = F/A)

# plot line 2
p =  p + geom_line(aes(x=X,y=Y), data=df1, colour="#56B4E9")    

# label line
direct.label(p, 'last.points')

However I get the following error message:

Error in direct.label.ggplot(p, "last.points") : 
  Need colour aesthetic to direct label.

I've tried adding several arguments to the direct.label() function, but I don't understand what aesthetic argument should be used.

Donella answered 26/6, 2011 at 20:47 Comment(1)
Some five years later: Did the answer work for you?Encroach
D
17

Instead of using 2 dataframes, you could combine and melt them:

library(ggplot2)
library(directlabels)

# Variables
A = array(1000,100)
F = seq(length=100, from=0, by=10)
f = array(5,100)

# make data frame 1
df <- data.frame(X = F * f/A, Y = F/A)

# make data frame 2
df1 <- data.frame(X = F * f * 2/A, Y = F/A)

# merge both dataframes
df2 <- merge(df, df1, by = "X")

# melt them
df2m <- melt(df2, id = "X")

# plot 
p2 <- ggplot(df2m, aes(x = X, y = value, col = variable)) +
  geom_line() +
  scale_color_manual(values = rep("#56B4E9", 2))

direct.label(p2, 'last.points')

You can also use the new geom_dl from directlabels 2.0 if you want direct labels, but don't want to use the colour aesthetic:

install.packages("directlabels")
ggplot(df2m, aes(x = X, y = value))+
  geom_line(aes(group=variable))+
  geom_dl(aes(label=variable),method="last.points")

labeled ggplot

Dunaj answered 26/6, 2011 at 21:37 Comment(1)
thanks for your answer. I'm currently generating many lines using a loop; is the issue that I need the data to be all from the same data frame? I thought it would be easiest to show my problem using just two lines; in retrospect it may have confused the issue. Could I add the label after adding a line?Donella

© 2022 - 2024 — McMap. All rights reserved.