python - 用 imshow 绘制的时间序列

标签 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

最佳答案

使用 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

要添加颜色条,我建议查看 this answer它使用 fig.add_axes() 或查看 AxesDivider 的文档(我个人更喜欢)。

关于python - 用 imshow 绘制的时间序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42374729/

相关文章:

python - 如何使用按钮行为在kivy中制作圆形按钮?

python - 从另一个文件导入变量?

python - 在 NumPy 中跟踪多索引和修改值

python - 绘制在窄范围内采样的复杂信号的频谱的正确方法是什么?

python - PyQt 没有 button.clicked.connect 功能?

python - 概率标准化的二维直方图

python - np.loadtxt() 如何从txt文件中每隔一行加载? Python

python - 使用 2D 数组在 Python 中绘制颤动图

python - 为什么子图在 x 轴上产生空白区域?

python - matplotlib 自定义标记