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

拆分正负数据绘制折线图后,如何在X轴显示日期?

解决折线图正负分色后X轴不显示datetime的问题

问题描述

我要制作一款折线图,要求数据为负时线条显示红色,为正时显示绿色。参考拆分DataFrame正负数据分别绘图的方法,写出了如下代码:

plt.figure(figsize=(12,8))

new_df.Performance.where(new_df.Performance.ge(0), np.nan).plot(color='green')
new_df.Performance.where(new_df.Performance.lt(0), np.nan).plot(color='red')

plt.show()

这段代码能正常生成折线图,但X轴仅显示数字序号,无法显示已经转为datetime类型的Date列。尝试添加x='date'等写法均无效,寻求解决办法。

简化后的DataFrame示例

Date            Performance
8/2/2022 0:00   -1.01
8/2/2022 20:00  -0.0001
8/2/2022 20:00  0.0001
8/3/2022 0:00   0.19
8/4/2022 0:00   2
8/6/2022 0:00   0.0001
8/7/2022 0:00   -0.0001
8/8/2022 0:00   -5

注:Date列已转为datetime对象。


解决方法

核心问题是拆分后得到的Series没有关联Date列作为索引,导致绘图时默认使用数字索引。这里提供两种可行方案:

方案1:将Date列设为DataFrame索引(推荐)

把Date列设置为DataFrame的索引后,pandas绘图会自动使用datetime索引作为X轴:

import matplotlib.pyplot as plt
import numpy as np

# 将Date列设置为索引
new_df = new_df.set_index('Date')

plt.figure(figsize=(12,8))

# 直接对索引化后的列绘图
new_df.Performance.where(new_df.Performance.ge(0), np.nan).plot(color='green')
new_df.Performance.where(new_df.Performance.lt(0), np.nan).plot(color='red')

# 优化X轴显示(可选)
plt.xlabel('Date')
plt.xticks(rotation=45)  # 旋转日期标签避免重叠
plt.show()

方案2:绘图时显式指定X轴数据

如果不想修改原DataFrame的索引,可以在每次调用plot()时显式传入x参数指定Date列:

plt.figure(figsize=(12,8))

# 每次绘图都指定x为Date列
new_df.Performance.where(new_df.Performance.ge(0), np.nan).plot(x=new_df['Date'], color='green')
new_df.Performance.where(new_df.Performance.lt(0), np.nan).plot(x=new_df['Date'], color='red')

# 优化X轴显示(可选)
plt.xlabel('Date')
plt.xticks(rotation=45)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 15:32:50