【问题标题】:Matplotlib, matshow not aligned with gridspec when fig size biMatplotlib,当图大小bi时matshow与gridspec不对齐
【发布时间】:2020-04-22 14:31:37
【问题描述】:

我尝试使用 gridspec 将多种类型的图绘制在一起。我将它与 Jupyter Notebook 一起使用,我意识到当图形宽度大于单元格宽度时。 matshow 缩小了,不再与其他人对齐。

例如,当 figsize 的宽度小于单元格宽度时,一切正常。 .

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as grd
duration = 1
data1 = np.sin(2*np.pi*np.linspace(0, duration, 10000))
data2 = np.random.random((100,12))
fig = plt.figure(figsize=[15, 5], constrained_layout=True)
grid = grd.GridSpec(2, 2, figure=fig, height_ratios=[1, 1], width_ratios=[40, 1])


ax = plt.subplot(grid[0])
ax.plot(data1)

ax = plt.subplot(grid[2])
im = ax.matshow(data2.T, cmap=plt.get_cmap('inferno'), origin='lower')

ax = plt.subplot(grid[3])
cb = plt.colorbar(im, cax=ax)

然后当宽度大于单元格时。 .

fig = plt.figure(figsize=[20, 5], constrained_layout=True)
grid = grd.GridSpec(2, 2, figure=fig, height_ratios=[1, 1], width_ratios=[40, 1])


ax = plt.subplot(grid[0])
ax.plot(data1)

ax = plt.subplot(grid[2])
im = ax.matshow(data2.T, cmap=plt.get_cmap('inferno'), origin='lower')

ax = plt.subplot(grid[3])
cb = plt.colorbar(im, cax=ax)

是什么导致 matshow() 缩小,我该如何解决?我在 Python 3.7 和 Matplotlib 3.1.3

谢谢

【问题讨论】:

  • matshow 的纵横比是固定的。如果把图拉宽,matshow不一定会变宽,因为它是固定的纵横比,高度是约束维度。
  • 此外,如果您能够使用 constrained_layout,则不需要对颜色条执行 gridspec 技巧。
  • 我通过将 matshow 的方面设置为“自动”解决了这个问题。你能详细说明关于颜色条的第二点吗?我没有找到另一种解决方案让 matshow 与其他图对齐,同时拥有颜色条
  • ``` import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(2, 1, constrained_layout=True) pc = ax[0].matshow(np.random. rand(20, 20), aspect='auto') fig.colorbar(pc, ax=ax[0]) ax[1].plot(np.random.rand(20)) plt.show() ```

标签: python matplotlib


【解决方案1】:

constrained_layout 的全部要点之一是颜色条的处理更加优雅。即你不需要width_ratios=[40, 1] hack。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2, 1, constrained_layout=True)
pc = ax[0].matshow(np.random.rand(20, 20), aspect='auto')
fig.colorbar(pc, ax=ax[0])
ax[1].plot(np.random.rand(20))
plt.show()

【讨论】:

    【解决方案2】:

    我试过你的代码。 如果使用 plt.show() 并最大化窗口:enter image description here

    【讨论】:

    • 嗨,我意识到问题是图形的宽度。我正在使用 Jupyter。当宽度大于单元格宽度时,就会出现问题。我重新表述了这个问题。所以我认为你不会看到 plt.show() 和弹出窗口的问题。
    猜你喜欢
    • 1970-01-01
    • 2016-11-30
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 2011-04-01
    • 2019-04-22
    • 2021-10-27
    相关资源
    最近更新 更多