Reputation: 427
I have a problem in matplotlib subplot, I have set these 5 subplot share axis, it should be have same lenth and scale, however, when i add the 5th subplot' colorbar, the axis doesnt math with others, what should i do? thanks very much
Upvotes: 0
Views: 755
Reputation: 12234
matplotlib
automatically resizes the axes and generate a second axis next to it to show the colorbar on. We can instead provide this second axis as follows:
import matplotlib.pyplot as plt
import numpy as np
fig, (ax1, ax2) = plt.subplots(nrows=2)
# Some demo data
x = np.linspace(0, 18)
y = np.linspace(0, 1)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + Y
# Something on axes 1
ax1.plot(x, np.sin(x))
# Plot the pcolormesh
pcm = ax2.pcolormesh(X, Y, Z)
# create color bar: the important part!
axColor = plt.axes([box.x0 + box.width * 1.05, box.y0, 0.01, box.height])
plt.colorbar(pcm, cax=axColor, orientation="vertical")
plt.show()
I learned this from this SO post, although I think the context is somewhat different.
The downside is that the saved figure will have some funny whitespace so you may want to think of alternative such as positioning the colorbar below or even on the plot.
Upvotes: 1