首页 > 解决方案 > ggplot - 行排序,一行在另一行之上

问题描述

这是我的例子:

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"))了,但没有用。

标签: ggplot2colorsline

解决方案


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

看到这个相关的线程,为什么我使用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 包(v0.3.0)于 2020-03-24 创建


推荐阅读