请发布可重现的代码以帮助我们回答您的问题。我们不知道是什么plot1
。
用于scale_colour_identity
告诉 ggplot2 将变量直接解释为颜色:
line_data <- data.frame(value = c(1,2), color = as.factor(c("blue", "green")))
ggplot(line_data) +
geom_hline(aes(yintercept = value, colour = color), line_data, linetype = "dashed", size = 0.5) +
scale_colour_identity()
编辑:要使新的颜色图例与现有图例兼容,请重新指定scale_colour_manual
. 您仍然会收到警告Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale.
,但它有效:
library(ggplot2)
# example plot1 with manual scale
plot1data = data.frame(x=c(1,2,3,4),
y=c(1,2,3,4),
color=factor(c(1,1,1,2)))
plot1 = ggplot(plot1data, aes(x=x, y=y, colour=color)) +
geom_point() +
scale_colour_manual(values=c('1'='green','2'='red'))
# data you want to add to the plot
line_data <- data.frame(value = c(1,2), color = as.factor(c("blue", "green")))
# assume you have the plot1 object but no access to the code that generated it
# extract colors from plot1
ggdata = ggplot_build(plot1)$data[[1]]
plot1_colours = ggdata$colour
names(plot1_colours) = ggdata$group
# use the values originally specified for plot1 (plot_colours); add additional custom values
plot1 +
geom_hline(aes(yintercept = value, colour = color), data = line_data, linetype = "dashed", size = 0.5) +
scale_colour_manual(values=c(plot1_colours, 'blue'='blue', 'green'='green'))
如果要从图例中删除某些值,请指定中断:
plot1 +
geom_hline(aes(yintercept = value, colour = color), data = line_data, linetype = "dashed", size = 0.5) +
scale_colour_manual(values=c(plot1_colours, 'blue'='blue', 'green'='green'), breaks = names(plot1_colours))