ggplot - 行排序,一行在另一行之上

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

这是我的例子:

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

外观如下:

我希望红线在蓝线重合的任何地方都位于蓝线之上。我尝试了 scale_color_manual(values = c("forecast" = "red" ,"actual" = "blue")),但没有成功。

更改因子水平顺序。也不要忘记更改组。

,为什么我用了scales::hue()等等

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

reprex package (v0.3.0)

于 2020 年 3 月 24 日创建