Reputation: 6958
Hi can I add an additional legend to a ggplot. Like the following code
d <- melt(as.matrix(data.frame(y1=1/(1:10),y2=1/(10:1))))
ggplot(d, aes(x=Var1, y=value,fill=Var2)) + geom_bar(stat="identity",position='dodge')
This generates a nice legend containing the name of my dataframe. But is it possible to put in an extralegend, that contains some extra information generated from the data.
In the standard R, I would add the additional legend like
d<-data.frame(y1=1/(1:10),y2=2*1/(10:1))
barplot(t(d),beside=T)
legend("top",paste("sums:",apply(d,2,sum)))
Thanks
Upvotes: 2
Views: 2649
Reputation: 4795
This seems to work for me.
plot.new()
d <- melt(as.matrix(data.frame(y1=1/(1:10),y2=1/(10:1))))
ggplot(d, aes(x=Var1, y=value,fill=Var2)) +
geom_bar(stat="identity",position='dodge')
then the exciting stuff.
legend('top',paste("sums:",tapply(d$value,d$Var2,sum)))
I changed the apply statement to work on the molten data.
I am not aware of a ggplot solution, but I would love to see one.
Upvotes: 2