如何在Python中基于1或0对背景进行着色
当y=1时,我希望x的图形背景为灰色,当y=0时,背景为白色如何在Python中基于1或0对背景进行着色,python,background,Python,Background,当y=1时,我希望x的图形背景为灰色,当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); 您可以尝试使用循环手动绘制矩形,而不是: import matplotlib.pyplot as plt import mat
#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);
您可以尝试使用循环手动绘制矩形,而不是:
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()
请提供一份详细的报告。如果不知道这些额外的变量是什么,就不清楚你在问什么。