0
    line_data <- data.frame(value = c(1,2), color = as.factor(c("blue", "green"))
      plot1 <- plot1 +
        geom_hline(aes(yintercept = value, colour = color), line_data, linetype = "dashed", size = 0.5)

以上是我的代码片段。无论我为color列分配什么,它都会被忽略。我可以分配整数或连续数字。它将被忽略。

编辑:

原因是因为plot1已经scale_color_manual添加了一个。现在的挑战变成了如何让它工作而不必删除scale_color_manual

4

1 回答 1

1

请发布可重现的代码以帮助我们回答您的问题。我们不知道是什么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))

在此处输入图像描述

于 2022-02-03T21:00:08.273 回答