指定颜色后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")
转换后的数据结构示例:
| Year | TimeOfDay | Count_Type | Count |
|---|---|---|---|
| 2003 | Midnight | Delay_Count | 9934 |
| 2003 | Midnight | Total_Count | 53321 |
| 2003 | Morning | Delay_Count | 544278 |
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
相关产品推荐
相关产品推荐

