Join GitHub today
colorbar might shrink plots if used with twinx #8823
Changing plot alignment for different placing of colorbar() in twinx plot
If one combines a
I am not sure if this is a bug or just wrong usage.
Code for reproduction
import numpy as np import matplotlib.pyplot as plt data = np.random.random((64, 128)) * 2.0 x = np.arange(128) y = np.arange(64) plt.pcolormesh(x, y, data) #plt.colorbar() --> here it works fine plt.twinx() plt.colorbar() # --> here it gives wrong x values for the orange plot plt.plot(x, np.sin(x/10), color="orange", lw=4) plt.show()
Next to the confusing layout the plot shows actually a wrong graph:
I am not sure if this is a bug or a wrong usage of matplotlib. In any case the wrong extent of the (in this case) orange plot is a dangerous behavior that might lead to misinterpretations of the data.
I installed matplotlib via pip.
I would call it a shortcoming of the twinx implementation: it makes a second Axes at the same position as the first, but it has no mechanism for ensuring that if the position of either is subsequently changed, the position of the other is also changed to match it. Ideally, the position of both Axes would be the same object so that it would not be necessary to use callbacks to keep them synchronized. There are several attributes related to position, so I'm not sure whether this would be a simple change, a difficult one, or a complete can of worms.
#9082 addresses this (though you can't use the pyplot interface)
data = np.random.random((64, 128)) * 2.0 x = np.arange(128) y = np.arange(64) fig, ax = plt.subplots(constrained_layout=True) pcm = ax.pcolormesh(x, y, data) #plt.colorbar() --> here it works fine ax2 = ax.twinx() fig.colorbar(pcm) # --> here it gives wrong x values for the orange plot ax2.plot(x, np.sin(x/10), color="orange", lw=4) plt.show()