如何在Python中将3D函数绘制为2D色彩图?

16 投票
4 回答
32011 浏览
提问于 2025-04-16 12:57

有没有什么Python库可以让我画出z = f(x,y)这样的图,其中z的值用颜色在一张密集的栅格图像中表示(而不是用一堆散点图的颜色)?如果有的话,我该用哪个函数呢?

看起来matplotlib.pyplot中的一些等高线函数差不多能满足我的需求,但它们会画出等高线,而我并不想要那些线。

4 个回答

1

在这里要给应得的赞誉:这只是对Andre Holzner回答的一个小改动。如果你觉得有帮助,请给他点赞!

import pylab

def f(x, y):
    return pylab.cos(x) + pylab.sin(y)

xx = pylab.linspace(-5, 5, 100)
yy = pylab.linspace(-5, 5, 100)
zz = pylab.zeros([len(xx), len(yy)])

for i in xrange(len(xx)):
    for j in xrange(len(yy)):
        zz[j, i] = f(xx[i], yy[j])

pylab.pcolor(xx, yy, zz)
pylab.show()

这种写法可能更容易理解,因为它只用了最基本的数组维度和索引。它依赖于以下一点(摘自文档)。

如果X和Y中有一个或两个是1维数组或列向量,它们会根据需要被扩展成合适的2维数组,从而形成一个矩形网格。

8

看看 matplotlibpcolorimshow 的文档吧。

另一个不错的起点是去看看 matplotlib 的图库,看看有没有你想要的图表类型,然后可以用那里的示例代码作为你自己工作的起点:

http://matplotlib.sourceforge.net/gallery.html

9

这里有一个简单的具体例子(对于那些不能接受矩阵作为 xy 参数的函数也适用):

# the function to be plotted
def func(x,y):    
    # gives vertical color bars if x is horizontal axis
    return x

import pylab

# define the grid over which the function should be plotted (xx and yy are matrices)
xx, yy = pylab.meshgrid(
    pylab.linspace(-3,3, 101),
    pylab.linspace(-3,3, 111))

# indexing of xx and yy (with the default value for the
# 'indexing' parameter of meshgrid(..) ) is as follows:
#
#   first index  (row index)    is y coordinate index
#   second index (column index) is x coordinate index
#
# as required by pcolor(..)

# fill a matrix with the function values
zz = pylab.zeros(xx.shape)
for i in range(xx.shape[0]):
    for j in range(xx.shape[1]):
        zz[i,j] = func(xx[i,j], yy[i,j])

# plot the calculated function values
pylab.pcolor(xx,yy,zz)

# and a color bar to show the correspondence between function value and color
pylab.colorbar()

pylab.show() 

撰写回答