简体   繁体   中英

How to properly show a colorbar in a polar graph (contour plot of half a circle)?

I am plotting a big matrix of temperature (for each r and theta of a circle) in a polar graph using Pyplot from matplotlib. So far, everything works fine with what I've done :

space_theta = radians(linspace(0, 180, M))
space_r = arange(0, a, delta_r)

r, theta = meshgrid(space_theta, space_r)

fig, axes = plt.subplots(subplot_kw=dict(projection='polar'))
axes.contourf(r, theta, T[W-1]) #T[W-1] is the temperatures I want to plot (T is a 3D matrix, so T[W-1] is a matrix)

axes.set_thetamin(0)
axes.set_thetamax(180)

plt.show()

With this, I get the following :

在此处输入图片说明

Now the only thing I want is to add a color legend, indicating which color corresponds to which temperature. It should look like this (only focus on the legend) :

在此处输入图片说明

I searched on several websites but didn't manage to find out how to do this. Each time the method used for plotting the graph was different. I tried using colorbar(), which solved problems for everyone, but I got an error ("No mappable was found to use for colorbar creation").

PS: If possible, I would like to show the max and min values on the color legend.

You can use plt.colorbar with the result of axes.contourf as first parameter. You'll notice the default colorbar will be much too large. To shrink it, use shrink=.6 to get it similar to your contourplot. Now, you'll notice it will be too close to the plot. This can be adjusted with pad=0.08 .

Note that the numpy library has lots of functions with similar names as other libraries. To make clear that you're using numpy functions, it is good practise to import numpy as np .

Here is a more complete example:

from matplotlib import pyplot as plt
import numpy as np

M = 100
a = 1
delta_r = 0.01
space_theta = np.radians(np.linspace(0, 180, M))
space_r = np.arange(0, a, delta_r)
T = np.random.uniform(-30, 40, M * len(space_r)).reshape((M, len(space_r)))

r, theta = np.meshgrid(space_theta, space_r)

fig, axes = plt.subplots(subplot_kw=dict(projection='polar'))
contourplot = axes.contourf(r, theta, T)
axes.set_thetamin(0)
axes.set_thetamax(180)
plt.colorbar(contourplot, shrink=.6, pad=0.08)

plt.show()

示例图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM