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

Pandas 1.5.3折线图叠加散点图后散点消失的问题

Pandas 1.5.3中折线图叠加散点图不显示的解决方法

修复方案1:转换日期格式适配matplotlib轴

将Pandas Timestamp转换为matplotlib可识别的日期数值,确保坐标映射正确:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

s = pd.Series(np.random.randn(100))
s.index = pd.period_range(start="2000", freq="M", periods=100).to_timestamp()

f, ax = plt.subplots()
s.plot(ax=ax)
# 转换Timestamp为matplotlib日期数值
ax.scatter(mdates.date2num(s.index), s, color="red")
plt.show()

修复方案2:调整绘图顺序

先绘制散点图,再绘制折线图,让Pandas自动适配轴格式:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

s = pd.Series(np.random.randn(100))
s.index = pd.period_range(start="2000", freq="M", periods=100).to_timestamp()

f, ax = plt.subplots()
ax.scatter(s.index, s, color="red")
s.plot(ax=ax)
plt.show()

问题原因

Pandas 1.5.x版本对时间序列绘图的轴处理逻辑做了变更:使用Series.plot()绘制折线图后,Axes的x轴会切换为matplotlib专属的日期轴格式,但直接传入Pandas Timestamp对象给ax.scatter时,会出现坐标映射不匹配的情况,导致散点不在当前显示范围内,视觉上像是被清除了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:15:00