如何使用matplotlib.pyplot根据(真/假的)数组为绘图的背景着色?
因此,例如,如果我的数组是(T,F,F,F,T,T),并且我选择了颜色“红色”和“蓝色”,则我需要将背景设为红色列,3个蓝色列,再加上2个红色。
N = 2000
tf = np.random.normal(size = N)
ctf = np.array([np.sum(tf[:1+i]) for i in range(N)])
fig, ax = plt.subplots()
tf2 = tf[None,:]
ax.imshow(tf2, cmap='RdYlGn', aspect = 'auto')
ax.plot(ctf,'k')
答案 0 :(得分:2)
您可以使用imshow:
import numpy as np
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
data = np.array([True, False, True])[ None, :]
ax.imshow(data, cmap = 'RdBu', aspect="auto")
ax.axis('off')
fig.show()
edit:交换轴以产生列 edit2:添加较大的imshow
import numpy as np
from matplotlib import pyplot as plt
N = 2000
tf = np.random.normal(size = N)
ctf = np.array([np.sum(tf[:1+i]) for i in range(N)])
fig, ax = plt.subplots(2, sharex = 'all', \
gridspec_kw = dict(\
height_ratios = [5, 1]))
tf2 = tf[None,:]
ax[0].plot(ctf,'k')
ax[1].imshow(tf2, cmap='RdYlGn', aspect = 'auto')
plt.subplots_adjust(hspace = 0)
编辑3:
import numpy as np
from matplotlib import pyplot as plt
N = 2000
tf = np.random.normal(size = N)
ctf = np.array([np.sum(tf[:1+i]) for i in range(N)])
fig, ax = plt.subplots()
tf2 = tf[None,:]
ax.plot(ctf,'k')
ax.imshow(tf2, cmap='RdYlGn', aspect = 'auto', extent =[0, ctf.shape[0], ctf.min(), ctf.max()])
答案 1 :(得分:0)
想要在绘图上绘制矩形的声音。 (请参阅matplotlib: how to draw a rectangle on image。如果要在其他数据后面放置矩形,请在创建矩形时将其zorder
设置为负数。