2011-06-26 27 views
6

我試圖用directlabels包標註兩條線我有一個簡單的情節(我使用ggplot2如何使用directlabels和ggplot2?

enter image description here

我的代碼如下:

# 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') 

然而我收到以下錯誤消息:

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

我試着添加幾個參數到direct.label()功能,但我不明白應該使用什麼美學參數。

+0

大約五年後:做了回答對你的工作? – MERose

回答

13

而不是使用2個dataframes的,你可以結合並使其熔融:

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') 

您還可以使用從directlabels 2.0新geom_dl如果你想直接的標籤,但不希望使用的顏色美學:

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

+0

感謝您的回答。我目前正在使用循環生成很多行;是我需要數據全部來自同一個數據框的問題?我認爲用兩條線顯示我的問題最容易;回想起來,它可能會混淆這個問題。添加一行後可以添加標籤嗎? – djq