Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

colors

ggplot2

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 red and blue. I tried it without (first code) and with (second) 'scale_color_manual', also tried with colour insted of color, with the same result:

fisrt code:

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

second code:

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

enter image description here

like image 630
or keissar Avatar asked Jan 01 '18 17:01

or keissar


1 Answers

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 is usually the preferred way.

like image 72
markus Avatar answered Oct 13 '22 20:10

markus