J_yang
J_yang

Reputation: 2822

Matplotlib, matshow not aligned with gridspec when fig size bi

I tried to use gridspec to plot multiple types of plots together. I use it with Jupyter Notebook, I realise that when the figure width is bigger than the cell width. The matshow shrunk and no longer aligned with others.

For example, when figsize's width is smaller than the cell width, everything is fine. .

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)

enter image description here

Then when the width is bigger than the cell. .

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)

enter image description here

What is causing the matshow() to shrink and how can I fix it? I am on Python 3.7 with Matplotlib 3.1.3

Thanks

Upvotes: 0

Views: 688

Answers (2)

Jody Klymak
Jody Klymak

Reputation: 5912

One of the whole points of constrained_layout is colorbars are dealt with more gracefully. i.e. you don't need the 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()

enter image description here

Upvotes: 1

Davide Trepiccione
Davide Trepiccione

Reputation: 1

i'm tried your code. If you use plt.show() and maximizes the window:enter image description here

Upvotes: 0

Related Questions