我想绘制一个true/false
或active/deactive
二进制数据,类似于下图:
水平轴是时间,垂直轴是某些实体(这里是一些传感器),它们是活动的(白色)或非活动的(黑色)。如何使用pyplot
绘制此类图表。
我搜索了这些图表的名称,但我找不到它。
答案 0 :(得分: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')
然后你只需从某处获得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)
创建
然而,插值在这里不一定是好事。为了使不同的行更容易分离,可以使用颜色:
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)
创建
当然,你会想要使用一些不那么奇怪的颜色作为着色方案,但这完全取决于你的艺术观点。这里的诀窍是行True
上的所有n
元素都具有值n+1
,并且False
中的所有0
元素都是data_color
。这使得可以创建颜色映射。当然,如果你想要一个有两种或三种颜色的循环颜色图,只需使用data_color
中imshow
的模数,例如: data_color % 3
。