时间序列用imshow绘制

时间:2017-02-21 18:05:48

标签: python numpy matplotlib

尽管我不确定它是否完全清晰,但我尽量使标题尽可能清晰。 我有三个系列的数据(事件的数量)。我想做三个时间序列的子图。你会发现我能想到的最好的东西。最后一个时间序列明显缩短了,这就是为什么它在这里不可见。

我还添加了相应的代码,这样你就可以更好地理解我为什么要这样做并以正确/聪明的方式为我提供建议。

import numpy as np
import matplotlib.pyplot as plt

x=np.genfromtxt('nbr_lig_bound1.dat')
x1=np.genfromtxt('nbr_lig_bound2.dat')
x2=np.genfromtxt('nbr_lig_bound3.dat')
# doing so because imshow requieres a 2D array
# best way I found and probably not the proper way to get it done
x=np.expand_dims(x, axis=0)
x=np.vstack((x,x))
x1=np.expand_dims(x1, axis=0)
x1=np.vstack((x1,x1))
x2=np.expand_dims(x2, axis=0)
x2=np.vstack((x2,x2))
# hoping that this would compensate for sharex shrinking my X range to 
# the shortest array 
ax[0].set_xlim(1,24)
ax[1].set_xlim(1,24)
ax[2].set_xlim(1,24)


fig, ax = plt.subplots(nrows=3, ncols=1, figsize=(6,6), sharex=True)
fig.subplots_adjust(hspace=0.001) # this seem to have no effect 

p1=ax[0].imshow(x1[:,::10000], cmap='autumn_r')
p2=ax[1].imshow(x2[:,::10000], cmap='autumn_r')
p3=ax[2].imshow(x[:,::10000], cmap='autumn')

这是我到目前为止所能达到的目标: Actual results

这是我希望拥有的计划,因为我无法在网上找到它。简而言之,我想删除两个上图中绘制数据周围的空白。作为一个更普遍的问题,我想知道如果imshow是获得这种情节的最佳方式(参见下面的预期结果)。

enter image description here

1 个答案:

答案 0 :(得分:2)

使用fig.subplots_adjust(hspace=0)将子图之间的垂直(高度)空间设置为零,但不调整每个子图中的垂直空间。默认情况下,plt.imshow的默认宽高比(rc image.aspect)通常设置为像素为正方形,以便您可以准确地重新创建图像。要更改此项,请使用aspect='auto'并相应地调整轴的ylim

例如:

# you don't need all the `expand_dims` and `vstack`ing.  Use `reshape`
x0 = np.linspace(5, 0, 25).reshape(1, -1)
x1 = x0**6
x2 = x0**2

fig, axes = plt.subplots(3, 1, sharex=True)
fig.subplots_adjust(hspace=0)

for ax, x in zip(axes, (x0, x1, x2)):
    ax.imshow(x, cmap='autumn_r', aspect='auto') 
    ax.set_ylim(-0.5, 0.5) # alternatively pass extent=[0, 1, 0, 24] to imshow
    ax.set_xticks([]) # remove all xticks
    ax.set_yticks([]) # remove all yticks

plt.show()

产量

enter image description here

要添加颜色栏,我建议您查看使用fig.add_axes()的{​​{3}}或查看this answer的文档(我个人更喜欢)。