如果您事先知道要添加的总行数,则可以使用适当的颜色和名称创建一个比例尺以用于scale_colour_manual
library(RColorBrewer)
library(plyr)
# a function to create a brewer palette of any length (kittens will be killed)
myBrewerPal <- function(pal = 'Spectral'){
colorRampPalette(brewer.pal(name = pal, n = 11))
}
# function to create a named vector of colours for a given
# vector x
create.palette <- function(x, pal = 'Spectral'){
ux <- sort(unique(x))
n <- length(ux)
setNames(myBrewerPal(pal)(n), ux)
}
# create a manual scale with the named values part
myPal <- scale_colour_manual(name = 'Gear', values = create.palette(factor(mtcars$gear)))
# the base plot (no lines)
baseplot <- ggplot(mtcars, aes(x=hp, y = disp, colour = factor(gear))) + myPal
# 1 line
baseplot + geom_line(subset = .(gear==3))
# 2 lines (gear = 3 is consistent)
baseplot + geom_line(subset = .(gear %in% 3:4))