user1700890
user1700890

Reputation: 7742

ggplot - line ordering, one line on top of the other

Here is my example:

library(ggplot2)

forecast <- c(2,2,1,2,2,3,2,3,3,3,3)
actual <- c(2,2,1,2,2,3,2,3,2,2,1)

my_df <- data.frame(forecast = forecast, actual = actual)
my_df$seq_order <- as.factor(1:NROW(my_df))
my_df <-gather(my_df, "line_type", "value", -seq_order)


ggplot(data=my_df, aes(x=seq_order, y = value,
  colour = line_type, group=line_type))+geom_line()+theme(legend.position="bottom")

Here is how it looks: plot

I would like to have red line to be on top of blue line everywhere where they coincide. I tried scale_color_manual(values = c("forecast" = "red" ,"actual" = "blue")), but it did not work.

Upvotes: 0

Views: 1503

Answers (1)

tjebo
tjebo

Reputation: 23807

Change the factor level order. Don't forget to change the group too.

See this related thread, why I used scales::hue() etc

library(tidyverse)

forecast <- c(2,2,1,2,2,3,2,3,3,3,3)
actual <- c(2,2,1,2,2,3,2,3,2,2,1)

my_df <- data.frame(forecast = forecast, actual = actual, seq_order = 1:11) 
my_df <-gather(my_df, line_type, value, -seq_order) %>% mutate(type = factor(line_type, levels = c('forecast','actual')))


ggplot(data=my_df, aes(x=seq_order, y = value, 
                       colour = type, group = type)) +
  geom_line()+
  theme(legend.position="bottom") +
  scale_color_manual(values = rev(scales::hue_pal()(2)))

Created on 2020-03-24 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions