Reputation: 239
fig, ax = plt.subplots(1, 2, subplot_kw=dict(projection='polar'))
ax[0].set_theta_zero_location("N")
ax[0].set_theta_direction(-1)
cax = ax[0].contourf(theta, r, values_2d,100)
cb = fig.colorbar(cax)
cb.set_label("Distance")
dax = ax[1].contourf(theta, r, d_values_2d,2)
db = fig.colorbar(dax)
db.set_label("Gradient")
plt.tight_layout(pad=0.4, w_pad=0.5)
plt.show()
The above figure has two plots on it. I can't find a way to make the colorbar
sit with each respective figure, though. Also, they're different sizes, why?
Upvotes: 0
Views: 1161
Reputation: 9810
You can pass the Axes
instance to which the colorbar should be attached to fig.colorbar()
with the keyword ax
. From the documentation:
ax : Axes, list of Axes, optional
Parent axes from which space for a new colorbar axes will be stolen. If a list of axes is given they will all be resized to make room for the colorbar axes.
Also, to avoid overlap, you can pass the keyword pad
. Here an a little bit altered version of your code:
from matplotlib import pyplot as plt
import numpy as np
#the coordinates
theta = np.linspace(0,2*np.pi, 100)
r = np.linspace(0,1,100)
#making up some data
theta,r = np.meshgrid(theta,r)
values_2d = np.sin(theta)*np.exp(-r)
d_values_2d = np.cos(theta)*np.sqrt(r)
fig, ax = plt.subplots(
1, 2, subplot_kw=dict(projection='polar'),
figsize = (10,4)
)
ax[0].set_theta_zero_location("N")
ax[0].set_theta_direction(-1)
cax = ax[0].contourf(theta, r, values_2d,100)
#the first altered colorbar command
cb = fig.colorbar(cax, ax = ax[0], pad = 0.1)
cb.set_label("Distance")
dax = ax[1].contourf(theta, r, d_values_2d,2)
#the second altered colorbar command
db = fig.colorbar(dax, ax = ax[1], pad = 0.1)
db.set_label("Gradient")
plt.tight_layout(pad=0.4, w_pad=0.5)
plt.show()
This gives the following result:
As to why you get the figure you get with your original code, I'm guessing that without the ax
keyword, colorbar
has to guess where to put the colorbar and it uses either the current active Axes instance or the last created one. Also, as both colorbars are attached to the same Axes there is less room for the actual plot, which is why the right plot in your example is way smaller than the left one.
Upvotes: 3