2011-07-06 83 views
29

在Paul的幫助下,我已經爲我的應用修改了mplot3d example code。代碼如下:用於matplotlib的色標plot_surface命令

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

代碼的偉大工程,以繪製表面。但是,當我嘗試將彩條添加到上述情節,我得到以下錯誤:

Traceback (most recent call last): 
    File "<ipython console>", line 1, in <module> 
    File "C:\Python26\lib\site-packages\spyderlib\widgets\externalshell\startup.py", line 122, in runfile 
    execfile(filename, glbs) 
File "C:\Documents and Settings\mramacha\My Documents\Python\Candela\test.py", line 22, in <module> 
    fig.colorbar(surf, shrink=0.5, aspect=5) 
    File "C:\Python26\lib\site-packages\matplotlib\figure.py", line 1104, in colorbar 
    cb = cbar.Colorbar(cax, mappable, **kw) 
    File "C:\Python26\lib\site-packages\matplotlib\colorbar.py", line 706, in __init__ 
    mappable.autoscale_None() # Ensure mappable.norm.vmin, vmax 
    File "C:\Python26\lib\site-packages\matplotlib\cm.py", line 261, in autoscale_None 
    raise TypeError('You must first set_array for mappable') 
TypeError: You must first set_array for mappable 

我會如此感激,如果有人能指導我這個問題。

帕布

+0

你更容易找到誰知道一個matplotlib郵件列表上的這些具體細節。 –

回答

42

您可以使用代理可映射對象,因爲你的面陣沒有映射。可映射只需將任何數組的值轉換爲由色彩映射定義的RGB色彩。

在你的情況要與Z1陣列要做到這一點:

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

這個答案利用了數據在0-1範圍內縮放的事實。如果不是,則標量可映射將被定義爲'm = cm.ScalarMappable(cmap = surf.cmap,norm = surf.norm)'。 – pelson