Had*_*adi 11 python plot matplotlib scipy
我想绘制true/false或active/deactive类似下面的图片二进制数据:

水平轴是时间,垂直轴是一些活动(白色)或非活动(黑色)的实体(这里是一些传感器).如何使用绘制这样的图形pyplot.
我搜索找到这些图的名称,但我找不到它.
DrV*_*DrV 20
你在寻找的是imshow:
import matplotlib.pyplot as plt
import numpy as np
# get some data with true @ probability 80 %
data = np.random.random((20, 500)) > .2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data, aspect='auto', cmap=plt.cm.gray, interpolation='nearest')
Run Code Online (Sandbox Code Playgroud)
然后你只需要从某个地方获得Y标签.

您的问题中的图像似乎在图像中有一些插值.让我们再设几件事:
import matplotlib.pyplot as plt
import numpy as np
# create a bit more realistic-looking data
# - looks complicated, but just has a constant switch-off and switch-on probabilities
# per column
# - the result is a 20 x 500 array of booleans
p_switchon = 0.02
p_switchoff = 0.05
data = np.empty((20,500), dtype='bool')
data[:,0] = np.random.random(20) < .2
for c in range(1, 500):
r = np.random.random(20)
data[data[:,c-1],c] = (r > p_switchoff)[data[:,c-1]]
data[-data[:,c-1],c] = (r < p_switchon)[-data[:,c-1]]
# create some labels
labels = [ "label_{0:d}".format(i) for i in range(20) ]
# this is the real plotting part
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data, aspect='auto', cmap=plt.cm.gray)
ax.set_yticks(np.arange(len(labels)))
ax.set_yticklabels(labels)
Run Code Online (Sandbox Code Playgroud)
创建

然而,插值在这里不一定是好事.为了使不同的行更容易分离,可以使用颜色:
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
# create a bit more realistic-looking data
# - looks complicated, but just has a constant switch-off and switch-on probabilities
# per column
# - the result is a 20 x 500 array of booleans
p_switchon = 0.02
p_switchoff = 0.05
data = np.empty((20,500), dtype='bool')
data[:,0] = np.random.random(20) < .2
for c in range(1, 500):
r = np.random.random(20)
data[data[:,c-1],c] = (r > p_switchoff)[data[:,c-1]]
data[-data[:,c-1],c] = (r < p_switchon)[-data[:,c-1]]
# create some labels
labels = [ "label_{0:d}".format(i) for i in range(20) ]
# create a color map with random colors
colmap = matplotlib.colors.ListedColormap(np.random.random((21,3)))
colmap.colors[0] = [0,0,0]
# create some colorful data:
data_color = (1 + np.arange(data.shape[0]))[:, None] * data
# this is the real plotting part
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data_color, aspect='auto', cmap=colmap, interpolation='nearest')
ax.set_yticks(np.arange(len(labels)))
ax.set_yticklabels(labels)
Run Code Online (Sandbox Code Playgroud)
创建

当然,你会想要使用一些不那么奇怪的着色方案,但这完全取决于你的艺术观点.这里的诀窍是True行上的所有元素n都有值n+1,并且所有False元素都0在data_color.这使得可以创建颜色映射.当然,如果你想要一个有两种或三种颜色的循环颜色图,只需使用data_colorin 的模数imshow,例如data_color % 3.