R - ggplot line color (using geom_line) doesn't change

前端 未结 1 1759
我在风中等你
我在风中等你 2020-12-11 19:38

When ploting 2 lines on one plot with ggplot(geom_line) the color of the line doesn\'t compre to the color that I set. I want the lines black and blue, but the outcome is re

相关标签:
1条回答
  • 2020-12-11 20:16

    Your first code should be

    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")
    

    You need to put color outside aes().

    For your second code you need to reshape your data from wide to long format. You can do this in many ways, the following should work for you.

    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'))
    

    In the first plot we set an aesthetic to a fixed value, in each call to geom_line(). This creates two new variables containing only the value "black" and "blue", respectively. In OP's example the values "black" and "blue" are then scaled to red and lightblue and a legend is added.

    In the second plot we map the colour aesthetic to a variable (key in this example). This usually the preferred way.

    0 讨论(0)
提交回复
热议问题