如何在绘制矩形时索引日期

时间:2018-05-22 10:41:05

标签: python datetime

对于数据分析,我想创建一个灰色条纹背景的图形。背景是灰色还是白色取决于不同阵列中的值(1或0)。这个数字看起来像这样:

enter image description here

import matplotlib.patches as patches

idx = np.linspace(0, nr_burst, nr_burst)
x = total #length nr_burst 
y = tide #zeros and ones of length nr_burst

fig, ax = plt.subplots(1, figsize=(15,5))
ax.plot(idx, x)
rect_height = np.max(x)
rect_width = 1

for i, draw_rect in enumerate(y):
    if draw_rect:
        rect = patches.Rectangle(
            (i, 0),
            rect_width,
            rect_height,
            linewidth=1,
            edgecolor='lightgrey',
            facecolor='lightgrey',
            fill=True
        )
        ax.add_patch(rect)

plt.show();

但是,我希望x轴给出日期而不是数据的索引。当我尝试用日期(长度为nr_burst的datetime.datetime对象)替换idx时,它给了我错误:float()参数必须是字符串或数字,而不是' datetime.datetime'。

这是代码:

import matplotlib.patches as patches

idx = dates #with length nr_burst as well
x = total #length nr_burst 
y = tide #zeros and ones of length nr_burst

fig, ax = plt.subplots(1, figsize=(15,5))
ax.plot(idx, x)
rect_height = np.max(x)
rect_width = 1

for i, draw_rect in enumerate(y):
    if draw_rect:
        rect = patches.Rectangle(
            (dates[i], 0),
            rect_width,
            rect_height,
            linewidth=1,
            edgecolor='lightgrey',
            facecolor='lightgrey',
            fill=True
        )
        ax.add_patch(rect)

plt.show();

我希望我在解释我想要达到的目标时已经足够清楚了。

1 个答案:

答案 0 :(得分:0)

您的代码可由converting dates to datenums修复:

import matplotlib.dates as mdates
datenums = mdates.date2num(dates)

然后使用datenums定义矩形:

patches.Rectangle((datenums[i], 0),...)

例如,

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

nr_burst = 50
dates = (np.array(['2000-01-01'], dtype='datetime64[D]') 
         + ((np.random.randint(1, 10, size=nr_burst).cumsum()).astype('<timedelta64[D]')))
idx = dates #with length nr_burst as well
x = np.random.random(nr_burst).cumsum() #length nr_burst 
y = np.random.randint(2, size=nr_burst) #zeros and ones of length nr_burst
datenums = mdates.date2num(dates)

fig, ax = plt.subplots(1, figsize=(15,5))
ax.plot(idx, x)
rect_height = np.max(x)
rect_width = 1

for i, draw_rect in enumerate(y):
    if draw_rect:
        rect = patches.Rectangle(
            (datenums[i], 0),
            rect_width,
            rect_height,
            linewidth=1,
            edgecolor='lightgrey',
            facecolor='lightgrey',
            fill=True
        )
        ax.add_patch(rect)

plt.show()

enter image description here

或者,你可以use ax.axvspan to create the hightlighted regions

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

nr_burst = 50
dates = (np.array(['2000-01-01'], dtype='datetime64[D]') 
         + ((np.random.randint(1, 10, size=nr_burst).cumsum()).astype('<timedelta64[D]')))
idx = dates #with length nr_burst as well
x = np.random.random(nr_burst).cumsum() #length nr_burst 
y = np.random.randint(2, size=nr_burst) #zeros and ones of length nr_burst
datenums = mdates.date2num(dates)

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

for datenum, yi in zip(datenums, y):
    if yi:
        ax.axvspan(datenum, datenum+1, facecolor='red', alpha=0.5)

plt.show()

enter image description here