You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

指定颜色后ggplot仍显示黑白?飞行数据折线图配色问题

解决ggplot折线图配色失效(黑白显示)的问题

问题根源

你的代码存在两个核心问题导致配色不生效:

  • 数据为宽格式,你用两个geom_line分别绘制Delay_Count和Total_Count,但每个geom_line的color仅映射了Year(水平为2003/2004/2005)。
  • scale_color_manual中定义的颜色键是"2003 Delay_Count"这类组合值,与aes(color=Year)的映射变量完全不匹配,ggplot无法找到对应颜色,因此默认使用黑白样式。

解决方案:转长格式数据+统一映射

1. 转换数据格式

先用tidyr::pivot_longer将宽数据转为长数据,把Delay_Count和Total_Count合并为一个分类变量,方便统一映射颜色:

library(tidyr)
# 转换为长格式
All_Flights_Long <- pivot_longer(All_Flights_Combined_TimeOfDay,
                                 cols = c(Delay_Count, Total_Count),
                                 names_to = "Count_Type",
                                 values_to = "Count")

转换后的数据结构示例:

YearTimeOfDayCount_TypeCount
2003MidnightDelay_Count9934
2003MidnightTotal_Count53321
2003MorningDelay_Count544278

2. 修改绘图代码

使用转换后的长数据,在aes中通过interaction(Year, Count_Type)生成你需要的组合分类,再与scale_color_manual的键匹配:

library(ggplot2)

timeofday_plot <- ggplot(All_Flights_Long, 
                         aes(x = TimeOfDay, y = Count, 
                             group = interaction(Year, Count_Type), 
                             color = interaction(Year, Count_Type))) +
  geom_line() +
  scale_x_discrete(limits = c("Midnight","Morning","Afternoon","Night")) +
  xlab("TimeOfDay") +
  ylab("Number of Flights") +
  ggtitle("Total number of Flights VS Flight Delays") +
  theme_classic() +
  scale_color_manual(
    values = c("2003.Delay_Count" = "red", 
               "2004.Delay_Count" = "green", 
               "2005.Delay_Count" = "blue", 
               "2003.Total_Count" = "orange", 
               "2004.Total_Count" = "yellow", 
               "2005.Total_Count" = "purple"),
    breaks = c("2003.Delay_Count",
               "2004.Delay_Count",
               "2005.Delay_Count",
               "2003.Total_Count", 
               "2004.Total_Count", 
               "2005.Total_Count"),
    labels = c("2003 Delay", "2004 Delay", "2005 Delay",
               "2003 Total", "2004 Total", "2005 Total") # 可选:美化图例标签
  )

timeofday_plot

关键说明

  • interaction(Year, Count_Type)会生成类似2003.Delay_Count的字符串,与scale_color_manual中的键对应(注意是点分隔)。如果偏好空格分隔,可改用paste(Year, Count_Type),同时将scale里的键改为带空格的形式。
  • 转长格式后只需一个geom_line,无需重复调用,代码更简洁逻辑更清晰。

内容的提问来源于stack exchange,提问作者Joseph Ng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 03:25:20