Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

python - Colorbar for matplotlib plot_surface command

I have modified the mplot3d example code for my application with Paul's help. The code reads:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)

x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
z1 = z * np.cos(0.5*x)

N = z1 / z1.max()  # normalize 0..1
surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=cm.jet(N), linewidth=0, antialiased=False, shade=False)

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

enter image description here

The code works great to plot the surface. But when I try to add a colorbar to the above plot, I get the following error:

Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
  File "C:Python26libsite-packagesspyderlibwidgetsexternalshellstartup.py", line 122, in runfile
    execfile(filename, glbs)
 File "C:Documents and SettingsmramachaMy DocumentsPythonCandelaest.py", line 22, in <module>
    fig.colorbar(surf, shrink=0.5, aspect=5)
  File "C:Python26libsite-packagesmatplotlibfigure.py", line 1104, in colorbar
    cb = cbar.Colorbar(cax, mappable, **kw)
  File "C:Python26libsite-packagesmatplotlibcolorbar.py", line 706, in __init__
    mappable.autoscale_None() # Ensure mappable.norm.vmin, vmax
  File "C:Python26libsite-packagesmatplotlibcm.py", line 261, in autoscale_None
    raise TypeError('You must first set_array for mappable')
TypeError: You must first set_array for mappable

I would be so grateful if someone is able to guide me with this.

Prabhu

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a proxy mappable object since your surface array is not mapped. The mappable simply converts the values of any array to RGB colors defined by a colormap.

In your case you want to do this with the z1 array:

import matplotlib.cm as cm
m = cm.ScalarMappable(cmap=cm.jet)
m.set_array(z1)
plt.colorbar(m)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...