R-ggplot线颜色(使用geom_line)不变

or *_*sar 3 r colors ggplot2

当用ggplot(geom_line)在一个图上绘制2条线时,该线的颜色不等于我设置的颜色。我想要黑色和蓝色线条,但结果是红色和蓝色。我在没有(第一个代码)和(第二个)'scale_color_manual'的情况下进行了尝试,还尝试了使用颜色插入颜色,结果相同:

第一个代码:

  ggplot(data=main_data) +
  # black plot
  geom_line(aes(x=vectors_growth_rate_with_predator, 
                y=disease_prevalnce_with_predator,
                color = "black")) + 
  # blue plot
  geom_line(aes(x=vectors_growth_rate_with_predator, 
                y=disease_prevalnce_without_predator,
                color = "blue"))
Run Code Online (Sandbox Code Playgroud)

第二个代码:

PrevVSGrowth = 
  ggplot(data=main_data) +
  # black plot
  geom_line(aes(x=vectors_growth_rate_with_predator, 
                y=disease_prevalnce_with_predator)) + 
  # blue plot
  geom_line(aes(x=vectors_growth_rate_with_predator, 
                y=disease_prevalnce_without_predator))

PrevVSGrowth + scale_color_manual(values=c(disease_prevalnce_with_predator= 'black',
                                           disease_prevalnce_without_predator = 'blue'))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

mar*_*kus 5

您的第一个代码应该是

ggplot(data=main_data) +
# black plot
geom_line(aes(x=vectors_growth_rate_with_predator, 
              y=disease_prevalnce_with_predator),
          color = "black") + 
# blue plot
geom_line(aes(x=vectors_growth_rate_with_predator, 
              y=disease_prevalnce_without_predator),
          color = "blue")
Run Code Online (Sandbox Code Playgroud)

您需要放在color外面aes()

对于第二个代码,您需要将数据的格式从宽格式转换为长格式。您可以通过多种方式执行此操作,以下应为您工作。

library(tidyverse)
main_data <- main_data %>% 
               gather(key, value, c("disease_prevalnce_with_predator",
                                    "disease_prevalnce_without_predator")
PrevVSGrowth <- ggplot(data=main_data) +
 geom_line(aes(x=vectors_growth_rate_with_predator, 
               y=value,
               col = key))

PrevVSGrowth + 
scale_color_manual(values = c(disease_prevalnce_with_predator= 'black',
                              disease_prevalnce_without_predator = 'blue'))
Run Code Online (Sandbox Code Playgroud)

在第一个情节中,每次调用时,我们都美学设置为固定值geom_line()。这将创建两个仅包含值“ black”和“ blue”的新变量。在OP的示例中,值“ black”和“ blue”随后被缩放为红色和浅蓝色,并添加了图例。

在第二个图中,我们将颜色美感映射到一个变量(key在此示例中)。这通常是首选方式。