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

绘制矩形时如何将日期设为Matplotlib图表的X轴索引

解决Matplotlib日期X轴下条件绘制灰色条纹的问题

你遇到的错误核心在于:patches.Rectangle需要数值类型的坐标参数,而datetime.datetime对象无法直接转换为浮点数。下面提供两种可行的解决方案:

方法一:将日期转换为Matplotlib兼容的数值坐标

Matplotlib自带了mdates.date2num()函数,可以把datetime对象转换成对应的数值格式,这样就能正常创建矩形补丁了。同时我们还需要根据日期间隔调整矩形宽度,让条纹宽度匹配实际时间跨度:

import matplotlib.patches as patches
import matplotlib.dates as mdates
import numpy as np
import matplotlib.pyplot as plt

# 假设你的dates是datetime类型数组
dates = ... 
x = total    # 你的数据数组,长度nr_burst
y = tide     # 0/1标记数组,长度nr_burst

fig, ax = plt.subplots(1, figsize=(15,5))
ax.plot(dates, x)

rect_height = np.max(x)
# 计算相邻日期的数值差,作为矩形宽度(适配时间跨度)
rect_width = mdates.date2num(dates[1]) - mdates.date2num(dates[0])

for i, draw_rect in enumerate(y):
    if draw_rect:
        # 把当前日期转换为Matplotlib数值坐标
        x_start = mdates.date2num(dates[i])
        rect = patches.Rectangle(
            (x_start, 0), rect_width, rect_height,
            linewidth=1, edgecolor='lightgrey', facecolor='lightgrey', fill=True
        )
        ax.add_patch(rect)

# 格式化X轴日期,避免标签重叠
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()

plt.show()

方法二:使用fill_between更简洁高效(推荐)

如果你的日期序列是连续的,用fill_between可以跳过循环创建补丁的步骤,直接根据0/1标记绘制条纹,而且自动适配日期坐标:

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

dates = ... 
x = total    
y = tide     

fig, ax = plt.subplots(1, figsize=(15,5))
ax.plot(dates, x)

rect_height = np.max(x)
# 根据y的0/1值生成对应的高度数组
fill_heights = np.where(y == 1, rect_height, 0)

# 绘制灰色条纹
ax.fill_between(dates, 0, fill_heights, color='lightgrey', alpha=0.5)

# 格式化X轴日期显示
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()

plt.show()

这种方法不仅代码更简洁,还能避免循环带来的性能损耗,尤其适合数据量较大的场景。

内容的提问来源于stack exchange,提问作者Rieneke van Noort

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:24:52