【发布时间】:2014-10-17 15:52:33
【问题描述】:
我想绘制类似于下图的true/false 或active/deactive 二进制数据:
横轴是时间,纵轴是一些实体(这里是一些传感器),它们是活动的(白色)或非活动的(黑色)。如何使用pyplot 绘制这样的图表。
我搜索了这些图表的名称,但找不到。
【问题讨论】:
标签: python matplotlib plot scipy
我想绘制类似于下图的true/false 或active/deactive 二进制数据:
横轴是时间,纵轴是一些实体(这里是一些传感器),它们是活动的(白色)或非活动的(黑色)。如何使用pyplot 绘制这样的图表。
我搜索了这些图表的名称,但找不到。
【问题讨论】:
标签: python matplotlib plot scipy
你要找的是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)
创造
当然,您会希望使用不那么奇怪的配色方案,但这完全取决于您的艺术观点。这里的诀窍是n 行上的所有True 元素都具有n+1 的值,并且所有False 元素在data_color 中都是0。这使得创建颜色映射成为可能。当然,如果您想要一个具有两种或三种颜色的循环颜色图,只需使用imshow 中的data_color 的模数,例如data_color % 3.
【讨论】: