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

解决Matplotlib绘制Pandas DataFrame时时间刻度标签重叠问题

问题描述

我有一个名为airtep_df的DataFrame,包含列AIRTEP(Int64)、AIRTEP_qc(Int64)和UTCTime。尝试用Matplotlib绘制该数据时,X轴的时间刻度标签重叠导致图表不可读。我尝试使用plt.xticks(rotation=45)旋转刻度标签,但图表消失了。所用脚本如下:

import matplotlib.pyplot as plt
import pandas as pd

index = (airtep_df['AIRTEP'] != 9999) & (airtep_df['AIRTEP_qc'] == 1)
selected_y = airtep_df.loc[index,'AIRTEP']
y = selected_y.values
selected_x = time_df.loc[index,'UTCTime']
x = selected_x.values
plt.plot(x[30],y[30])

问题原因

  1. 图表消失的直接原因:你在plt.plot()中只传入了x[30]和y[30]——这是单个数值而非数组,Matplotlib只会绘制一个极小的孤立点,肉眼几乎不可见;加上plt.xticks(rotation=45)后,刻度设置逻辑会因为无有效连续数据区域失效,最终导致图表完全消失。
  2. 刻度重叠的原因:如果UTCTime是字符串或未转换为datetime类型,Matplotlib会将其视为离散分类变量,强制显示所有标签,自然造成重叠;即便已是datetime类型,若时间点过于密集,默认刻度规则也会导致标签拥挤。

正确解决方案

步骤1:修复绘图数据的核心错误

首先要绘制完整的序列而非单个点,将plt.plot(x[30], y[30])修改为plt.plot(x, y),这样才能生成可观测的曲线。

步骤2:确保时间列是datetime类型

先检查UTCTime的数据类型,若不是datetime则先转换,同时避免索引错位(你的代码中selected_x来自time_df,但筛选条件基于airtep_df,容易导致数据不匹配):

# 转换airtep_df中的UTCT列为datetime类型
airtep_df['UTCTime'] = pd.to_datetime(airtep_df['UTCTime'])
# 直接从airtep_df筛选符合条件的数据,避免跨DataFrame索引错位
selected_data = airtep_df[(airtep_df['AIRTEP'] != 9999) & (airtep_df['AIRTEP_qc'] == 1)]

步骤3:优化时间刻度显示

方法1:Matplotlib原生优化(精细控制)

import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateFormatter, AutoDateLocator

# 绘图
fig, ax = plt.subplots()
ax.plot(selected_data['UTCTime'], selected_data['AIRTEP'])

# 设置自动日期刻度与格式化,Matplotlib会根据数据密度自动调整刻度数量
locator = AutoDateLocator()
formatter = AutoDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

# 旋转刻度标签,并调整底部间距避免标签被截断
plt.xticks(rotation=45)
plt.subplots_adjust(bottom=0.2)

plt.show()

方法2:Pandas内置绘图(简洁高效)

Pandas对datetime类型的支持更友好,会自动优化刻度布局:

import pandas as pd
import matplotlib.pyplot as plt

# Pandas直接绘图,自动处理时间刻度
ax = selected_data.plot(x='UTCTime', y='AIRTEP', figsize=(10,6))
# 旋转标签并调整底部间距
ax.tick_params(axis='x', rotation=45)
plt.subplots_adjust(bottom=0.2)

plt.show()

额外优化:手动设置刻度间隔

如果时间序列极密集,可以手动指定刻度间隔,比如每2小时显示一个刻度:

from matplotlib.dates import HourLocator, DateFormatter

# 接方法1的绘图代码,添加以下设置
ax.xaxis.set_major_locator(HourLocator(interval=2))
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d %H:%M'))

内容的提问来源于stack exchange,提问作者Qinghuan Li

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:17:50