使用 Matplotlib 中定义的 x 轴绘制矩形

Plot rectangle using defined x-axis in Matplotlib

我想使用 Matplotlib 使用定义的 xticks 和 ylim 绘制矩形,如下例所示:

import matplotlib.pyplot as plt

x = ['00:00', '01:00', '02:00', '03:00', '04:00' , '05:00', '06:00', '07:00', '08:00' ,'09:00' ,'10:00', '11:00', '12:00',
            '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00']

plt.ylim([1,10])

在这些限制下,使用 x 索引在下面打印一个矩形:

rect = Rectangle((x[4], x[7]), 4, 8, color='yellow')

最后,想法是有多个矩形。有没有不使用 date/time 函数的方法?

plt.Rectangle的参数是((x, y), width, height)。您可以绘制一个矩形,例如如下所示:

import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

x = ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
     '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00']
plt.figure(figsize=(15, 5))
plt.xticks(range(len(x)), x)
plt.ylim([1, 10])
x_start, x_end = 4, 7
y_start, y_end = 4, 8
ax = plt.gca()
ax.add_patch(plt.Rectangle((x_start, y_start), x_end - x_start, y_end - y_start,
                           facecolor=to_rgba('crimson', 0.5), edgecolor='black', lw=2))
plt.show()