0

我试图在 ggplot2 中获得一个图例,它将使用以下代码显示我的数据的标签和颜色:

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)

此时,valueVector = c("red", "blue", "green", "black"),

breakVector = c(“前”、“后”、“公里”、“VanKilled”)、

p 创建一个图,其中 front = red,rear = green,kms = blue,VanKilled = black。

如您所见,值的顺序已被打乱,随后颜色不是我试图将它们设置为的颜色。我找不到任何押韵或理由,每次制作新图表时似乎都不同。有谁知道如何解决这一问题?

4

1 回答 1

2

你在这件事上走错路了。ggplot2 使用一个框架来创建图形,这需要一些熟悉。您应该阅读一些介绍性材料。这是您示例的基本思想,

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()
于 2013-06-21T20:27:50.293 回答