2014-03-04 156 views
5

我想要實現像surf(x,y,z,c)在MATLAB中,這裏xyz功能是座標,c是一個變量的值,我可以用c定義顏色。我不知道如何用matplotlib來實現它。matplotlib中Matlab的surf(x,y,z,c)等價於什麼?

+1

你可以看看這個教程http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html – marsei

+1

我沒有」在matplotlib教程中找到像surf(x,y,z,c)這樣的函數 – bowang

+1

這實際上並不完全符合SO標準;包括你嘗試過的以及爲什麼它沒有工作/等等。然後我們可以從那裏幫助你。即使你說我閱讀了文檔,卻無法理解它們,你就會變得更好,而不是隻是要求其他人做你的功課。 –

回答

4

我使用的代碼是這樣做了(見Edgelines vanish in mplot3d surf when facecolors are specified):

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

fig = plt.figure() 
ax = fig.gca(projection='3d') 


#Create X and Y data 
x = np.arange(xmin, xmax, xstep) 
y = np.arange(ymin, ymax, ystep) 
X, Y = np.meshgrid(x, y) 


surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=C, antialiased=True) 

#Show the plot 
plt.show() 
3

你需要創建一個標量地圖,將存儲在陣列「C」中的值轉換成顏色值:

from matplotlib.colors import Normalize 
from matplotlib import cm 

import matplotlib.pyplot as plt 

# assuming X, Y, Z, C are given in correct format 
# Z and C have same dimensions 

min = C.min() 
max = C.max() 

# choose any colormap e.g. cm.jet, cm.coolwarm, etc. 
color_map = cm.RdYlGn # reverse the colormap: cm.RdYlGn_r 
scalarMap = cm.ScalarMappable(norm=Normalize(vmin=min, vmax=max), cmap=color_map) 

# outputs an array where each C value is replaced with a corresponding color value 
C_colored = scalarMap.to_rgba(C) 

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=C_colored, antialiased=True) 
0

這裏有一個方便的功能,其他兩個答案(https://stackoverflow.com/a/22176126/171761https://stackoverflow.com/a/23799389/171761)相結合,使您可以在一個單一的參數傳遞(光柵Z,像imshow)和顏色表,並計算X,Y和C (或允許你通過我N個Z,顏色表,還有一些X,Y和C):

def surf(Z, colormap, X=None, Y=None, C=None, shade=None): 
    if X is None and Y is None: 
     X, Y = meshgrid_of(Z) 
    elif X is None: 
     X, _ = meshgrid_of(Z) 
    elif Y is None: 
     _, Y = meshgrid_of(Z) 

    if C is None: 
     C = Z 

    scalarMap = cm.ScalarMappable(norm=Normalize(vmin=C.min(), vmax=C.max()), cmap=colormap) 

    # outputs an array where each C value is replaced with a corresponding color value 
    C_colored = scalarMap.to_rgba(C) 

    ax = gca(projection='3d') 

    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=C_colored, shade=shade) 

    return surf 


def meshgrid_of(A): 
    xx, yy = meshgrid(range(shape(A)[1]), range(shape(A)[0])) 
    return xx, yy 
相關問題