代码之家  ›  专栏  ›  技术社区  ›  user1700890

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

  •  0
  • user1700890  · 技术社区  · 5 年前

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

    下面是它的外观: plot

    scale_color_manual(values = c("forecast" = "red" ,"actual" = "blue")) ,但没有起作用。

    1 回复  |  直到 5 年前
        1
  •  1
  •   tjebo    5 年前

    更改因子级别顺序。别忘了也换一组。

    See this related thread 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)))
    

    于2020-03-24由 reprex package (第0.3.0版)