0

I have a graph which has 2 graphs stacked on top of each to allow for direct comparison. However, when I add a colour bar to my graph it makes the top graph wider then the colormap below it as seen below but I want the top line graph to be as wide as the color map below:

enter image description here

Using code:

import numpy as np 
import matplotlib.pyplot as plt 



x = 20,40,60,80,100
y = 0,0,0,30,100

x1 = [[20, 20, 20, 20, 20], [40, 40, 40, 40, 40], [60, 60, 60, 60, 60], [80, 80, 80, 80, 80], [100, 100, 100, 100, 100]]
y1 = [[1000, 2000, 3000, 4000, 5000],[1000, 2000, 3000, 4000, 5000],[1000, 2000, 3000, 4000, 5000],[1000, 2000, 3000, 4000, 5000],[1000, 2000, 3000, 4000, 5000]]
z1 = [[0,0,0,0,0], [0,1,2,1,0], [0,1,2,1,0], [0,20,100,20,0], [0,40,200,40,0]]



gridspec_kw = dict(
    height_ratios=(1, 2),
    hspace=0,
)

fig, axes = plt.subplots(
    nrows=2, ncols=1, sharex=True, gridspec_kw=gridspec_kw,
)

axes[0].plot(x,y)
cs = axes[1].pcolor(x1, y1, z1, cmap='RdBu')
plt.colorbar(cs)
plt.show()
15002941
  • 347
  • 2
  • 8

1 Answers1

1

The problem is that the colorbar is taking up some space in the subplot. You could use the solution from this question, and replace the plt.colorbar(cs) line with this code:

fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(cs, cax=cbar_ax)

enter image description here

Ivan Gorin
  • 303
  • 2
  • 12