你如何在ggplot2中制作自定义图例?

时间:2013-06-21 20:16:59

标签: r ggplot2

我正在尝试在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(“红色”,“蓝色”,“绿色”,“黑色”),

breakVector = c(“前方”,“后方”,“公里”,“范杀”),

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

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

1 个答案:

答案 0 :(得分: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()
相关问题