如何在Python中基于1或0为背景着色

时间:2018-05-17 11:04:41

标签: python background

我希望x的图形背景在y = 1时为灰色,在y = 0时为白色

    #some random data
    x = np.random.random(12)
    #0's and 1's
    y = [0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]

    plt.plot(np.linspace(0, 12, 12), x);

So it looks something like this代替this

1 个答案:

答案 0 :(得分:0)

您可以尝试使用循环手动绘制矩形:

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

idx = np.linspace(0, 12, 12)
x = np.random.random(12)
y = [0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1]

fig, ax = plt.subplots(1)
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='grey',
            facecolor='grey',
            fill=True
        )
        ax.add_patch(rect)

plt.show()

Output figure