2

I have a problem with a color bar in multiplot. The two plots are not aligned when I add the color bar. If I remove the color bar, the plots are aligned nicely.

How to resize the plots in multiplot? I just want to resize the width either lower or upper plot in oder to align the plots. Here is my code.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.gridspec as gridspec

fig = plt.subplots(2,figsize=(5, 8))
gs  = gridspec.GridSpec(2, 1, height_ratios=[ 3,2],hspace=0.0)

ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])

xx   = np.linspace(0,5,50)
yy   = np.linspace(0,5,50)
X, Y = np.meshgrid(xx, yy)
T = X**2 

norm = mpl.colors.Normalize(vmin=0,vmax=10)
pcm=ax1.pcolormesh(X,Y,T, norm =norm)
plt.colorbar(pcm, orientation="vertical", ax =ax1)

ax2.plot(xx, xx**2)

And, here is the result.

the result

Eiji
  • 155
  • 11

3 Answers3

3

You can try a horizontal bar orientation too.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.gridspec as gridspec

fig = plt.subplots(2,figsize=(5, 8))
gs  = gridspec.GridSpec(2, 1, height_ratios=[ 3,2],hspace=0.0)

ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])

xx   = np.linspace(0,5,50)
yy   = np.linspace(0,5,50)
X, Y = np.meshgrid(xx, yy)
T = X**2 

norm = mpl.colors.Normalize(vmin=0,vmax=10)
pcm=ax1.pcolormesh(X,Y,T, norm =norm)
plt.colorbar(pcm, orientation="horizontal", ax =ax1, pad=0.1)

ax2.plot(xx, xx**2)

enter image description here

Wonderworld
  • 101
  • 7
2

From Positioning the Color Bar answer we can add a new axis without grid spec

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(5,8))
ax1 = fig.add_subplot(211)  #Create 2x1 grid and declare ax1 as first plot
ax2 = fig.add_subplot(212)  #Create 2x1 grid and declare ax2 as second plot

xx   = np.linspace(0,5,50)
yy   = np.linspace(0,5,50)
X, Y = np.meshgrid(xx, yy)
T = X**2 

norm = mpl.colors.Normalize(vmin=0,vmax=10)
pcm=ax1.pcolormesh(X,Y,T, norm =norm)

cbaxes = fig.add_axes([0.95, 0.53, 0.03, 0.35]) #Add position (left, bottom, width, height)
cb = plt.colorbar(pcm, cax = cbaxes) 
ax2.plot(xx, xx**2)

Output

enter image description here

Pirate X
  • 3,023
  • 5
  • 33
  • 60
0

It seems I got a solution. But, I just add my own axis and put the color bar on that the defined axis. I am still wondering how to make this kind of plot easily.

fig  = plt.figure(2,figsize=(5, 8))
gs   = gridspec.GridSpec(2, 1, height_ratios=[ 3,2],hspace=0.0)

axes = fig.add_axes([0.25,0.425,0.78,0.455])

ax1  = plt.subplot(gs[0])
ax2  = plt.subplot(gs[1])

xx   = np.linspace(0,5,50)
yy   = np.linspace(0,5,50)
XX, YY = np.meshgrid(xx, yy)

TY = XX**2 
norm = mpl.colors.Normalize(vmin=0,vmax=10)
pcm =ax1.pcolormesh(XX,YY,TY, norm =norm)

plt.colorbar(pcm, orientation="vertical", ax =axes);

ax2.plot(xx, xx**2);

Here is a better plot.

enter image description here

Eiji
  • 155
  • 11