ifreak
ifreak

Reputation: 1756

add custom legend in ggplot2

I'm working with ggplot2 to generate some geom_line plots which i've already generated from another data.frame which is not important to mention here. but it also contains the same id value as the following dataframe.

I have this data frame called df:

id    X   Y     total
1   3214 6786   10000
2   4530 5470   10000
3   2567 7433   10000
4   1267 8733   10000
5   2456 7544   10000
6   6532 6532   10000
7   5642 4358   10000

What i want to do is create custom legend which present for a specific id the percentage of X and Y on each of the geom_line for when the id variable is the same. So basically for each geom_line of e.g(id=1, draw the percentage for that id in the geom_line plot)

I've tried to use geom_text, but the problem is that it's printing everything in one line which i cannot see anything of it.

how this can be done ??

EDIT

olddf dataframe is something like that:

id pos X Y Z
1
1.....
1
2
3
4
3 ......
.
.

that's the code that i've tried

for(i in df$id)
{
test = subset(olddf, id==i)
mdata <- melt(test, id=c("pos","id"))
pl = ggplot() + geom_line(data=mdata, aes(x=pos, y=value, color=variable)) + geom_text(data=df, aes(x=6000, y=0.1, label=(X*total)/100), size=5)
}

enter image description here

Upvotes: 1

Views: 1018

Answers (1)

Arun
Arun

Reputation: 118779

The answer (as discussed in chat) is quite straightforward:

Change geom_text(data = df, ...) to geom_text(data = df[df$id == i, ], ...)

Upvotes: 2

Related Questions