0
votes

I'm trying to get a legend in ggplot2 that will display the label and color of my data with this code:

valueVector <- vector()
breakVector <- vector()
foo <- as.data.frame(Seatbelts)
p <- ggplot(foo, aes(x=drivers, y=DriversKilled))  
p <- p + geom_line(aes(y = front, colour = "front"), size = .5)
valueVector <- c(valueVector,"red")
breakVector <- c(breakVector,"front") 
p <- p + geom_line(aes(y = rear, colour = "rear"), size = .5)
valueVector <- c(valueVector,"blue")
breakVector <- c(breakVector,"rear")
p <- p + geom_line(aes(y = kms/100, colour = "kms"), size = .5)
valueVector <- c(valueVector,"green")
breakVector <- c(breakVector,"kms")  
p <- p + geom_line(aes(y = VanKilled, colour = "VanKilled"), size = .5)
valueVector <- c(valueVector,"black")
breakVector <- c(breakVector,"VanKilled")
p <- p + scale_colour_manual("", values = valueVector, breaks = breakVector)

At this point, valueVector = c("red", "blue", "green", "black"),

breakVector = c("front", "rear", "kms", "VanKilled"),

and p creates a graph where front = red, rear = green, kms = blue, and VanKilled = black.

As you can see the order of the values has been shuffled, and subsequently the colors aren't what I tried to set them as. I can't find any rhyme or reason to this, it seems to be different every time I make a new graph. Does anyone know how to fix this?

1

1 Answers

2
votes

You're going the wrong way about this. ggplot2 uses a framework to create graphics, which takes some familiarity. You should read some introductory material. Here's the basic idea for your example,

d <- data.frame(Seatbelts)
d$kms <- d$kms/100

require(reshape2) # to transform the data into long format
m <- melt(d, meas = c("front", "rear", "kms", "VanKilled"))

# now we map the variables to aesthetic parameters
ggplot(m, aes(drivers, value, colour=variable)) +
  geom_line()