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

如何修正ggplot2双线图中Tmax与Tmin的颜色反转问题?

解决ggplot2双线图颜色反转及scale_color_manual报错问题

问题背景

你在使用ggplot2绘制最高/最低气温双线图时遇到两个问题:Tmax和Tmin的颜色显示反转;启用注释的scale_color_manual代码后,图表变为黑色且报错。

原数据

Date  Tmax  Tmin
1  25.6  18.2
2  26.2  16.6
3  23.8  17.9
4  26.3  16.9
5  26.7  17.6
6  27.8  17.6
7  28.0  17.7
8  25.5  17.9
9  26.2  16.8
10  27.2  18.3
11  25.3  16.4
12  27.2  16.8
13  25.3  17.4
14  24.6  17.8
15  26.2  17.9
16  22.8  17.7
17  27.4  18.2
18  25.2  18.2
19  25.8  16.9
20  26.3  16.4
21  22.1  16.4
22  25.2  16.0
23  25.2  15.6
24  26.6  17.4
25  28.0  18.6
26  25.3  18.6
27  24.1  18.3
28  26.5  16.6
29  25.2  16.8
30  28.9  16.7
31  27.1  16.8

原代码

library(ggplot2)

# Create a data frame
df_tminmax<-read.table("Tminmax.txt", header=TRUE, check.names=FALSE)
x = df_tminmax$Date

# Create a ggplot line plot
ggplot(df_tminmax, aes(x = x)) +
geom_line(aes(y = Tmax, color =  "red")) +
geom_line(aes(y = Tmin, color =  "blue")) +
labs(title = "Minimum and Maximum
 Temperatures, jan. 1950",
x = "Date",
y = "Temperature") +
theme(plot.title = element_text(hjust = 0.5))  #centering title
#scale_color_manual(values = c("Tmin" = "blue", "Tmax" = "red"))   # This turns plots black and gives error

#Add gridlines
grid(nx = NULL, ny = NULL, col = "lightgray", lty = "dotted")
ggsave("Tempplot.png")
dev.off()

问题原因

  1. 颜色映射逻辑错误:在aes()中设置color = "red"/"blue",并非直接指定线条颜色,而是将这两个字符串作为分类变量标签,ggplot会自动分配默认颜色,导致颜色与预期反转。
  2. scale_color_manual匹配失败:你指定的键是"Tmin"/"Tmax",但原代码的颜色变量是"red"/"blue",两者不匹配,ggplot无法找到对应颜色,默认显示黑色并报错。
  3. 网格线函数不兼容:grid()是基础绘图系统函数,与ggplot2不兼容,无法生效。

修正方案

1. 转换数据为长格式(tidy data)

ggplot2更适配长格式数据,使用tidyr包转换数据结构:

# 若未安装tidyr包,先执行 install.packages("tidyr")
library(tidyr)

# 将宽格式转换为长格式
df_long <- pivot_longer(df_tminmax, cols = c(Tmax, Tmin), 
                        names_to = "Temp_Type", values_to = "Temperature")

2. 修正后的完整绘图代码

library(ggplot2)

ggplot(df_long, aes(x = Date, y = Temperature, color = Temp_Type)) +
  geom_line() +
  labs(title = "Minimum and Maximum Temperatures, jan. 1950",
       x = "Date",
       y = "Temperature",
       color = "Temperature Type") +
  # 精准匹配温度类型与颜色
  scale_color_manual(values = c("Tmax" = "red", "Tmin" = "blue")) +
  # 居中标题+添加网格线
  theme(plot.title = element_text(hjust = 0.5),
        panel.grid = element_line(color = "lightgray", linetype = "dotted")) +
  ggsave("Tempplot.png")
dev.off()

关键修正说明

  • 将颜色映射到Temp_Type变量(即Tmax/Tmin),而非直接写颜色字符串。
  • scale_color_manual的键对应Temp_Type的取值,值对应目标颜色,实现精准匹配。
  • 用ggplot2原生的theme(panel.grid = ...)替代基础绘图的grid()函数,添加网格线。

内容的提问来源于stack exchange,提问作者Zilore Mumba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 15:17:32