seth127
seth127

Reputation: 2744

Manual legend labels for line graph ggplot2 in R

This seems like a fairly basic question, but I'm relatively new to ggplot2 and I can't seem to figure this out. If there is something basic about the "grammar" that I'm misunderstanding here, it would be great if someone could point me in the right direct. Or just telling me how to change these labels would be great...

Say I have this (fake) data:

avgTerms <- data.frame(itNum = seq(1,15),
                   i15 = runif(15,5,7),
                   i20 = runif(15,5.5,7.5),
                   i25 = runif(15,4,7),
                   i30 = runif(15,6,8))

I make a basic line plot with it like so:

#colour palette (colorblind-friendly)
cbb <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
#plot
avgTermsplot <- ggplot(data=avgTerms, aes(itNum, avgTerms[,2]))
avgTermsplot <- avgTermsplot + geom_line(aes(itNum, avgTerms[,2], colour=cbb[2]))
avgTermsplot <- avgTermsplot + geom_line(aes(itNum, avgTerms[,3], colour=cbb[3]))
avgTermsplot <- avgTermsplot + geom_line(aes(itNum, avgTerms[,4], colour=cbb[4]))
avgTermsplot <- avgTermsplot + geom_line(aes(itNum, avgTerms[,5], colour=cbb[5]))
avgTermsplot <- avgTermsplot + labs(x="Iteration Number", y="Avg # of Tags Applied")

print(avgTermsplot)

As you can see, the labels in the legend are the color codes. Not useful. I want them to be the column names from the data.frame. (As in, they should be i15, i20, etc.) I've tried a bunch of things, trying to assign them from the vector names(avgTerms)[2:5] but none of those things seem to work, so I won't list them all here. Is there a simple way to assign legend labels from a character vector?

Thank you very much for any help.

Upvotes: 1

Views: 1709

Answers (1)

erc
erc

Reputation: 10131

It's recommended to use data in long format for ggplot2, so melt your data first:

library(reshape2)
avgTerms.m <- melt(avgTerms, id.vars = "itNum")

And then assign the colours based on variable:

ggplot(data = avgTerms.m, aes(itNum, value, colour = variable)) +
  geom_line() +
  labs(x = "Iteration Number", y = "Avg # of Tags Applied") +
  scale_colour_manual(values = cbb)

enter image description here

Upvotes: 0

Related Questions