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

发布于 2024-10-20 08:03:55 字数 152 浏览 5 评论 0原文

是否有任何 python 库可以让我绘制 z = f(x,y) ,其中 z 表示为密集光栅化图像中的颜色(而不是一堆散点图点的颜色)?如果是这样,我该使用什么功能?

看起来 matplotlib.pyplot 中的一些轮廓函数接近我想要的,但它们绘制轮廓线,而我不想要这样。

Are there any python libraries that will let me plot z = f(x,y) where z is represented as the color in a densely rasterized image (as opposed to the color of a bunch of scatterplot points) ? If so, what function do I use?

It looks like some of the contour functions in matplotlib.pyplot come close to what I want, but they draw contour lines and I don't want that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

满地尘埃落定 2024-10-27 08:03:56

为了扩展我上面的评论,这里有一些在网格上计算函数的可能方法

boffi@debian:~/Documents/tmp$ cat grid.py 
import numpy as np

def z(x,y):
  return np.sin(np.sqrt(x*x+y*y))

x = np.linspace(-1,1,11)
y = np.linspace(-2,2,21)

# naive

Z0 = np.zeros((len(y), len(x)))
for i, X in enumerate(x):
    for j, Y in enumerate(y):
        Z0[j,i] = z(X,Y)

# trampoline on a double list comprehension,
# it is possibly faster, sure it uses more memory

Z1 = np.array([[z(X,Y) for X in x] for Y in y])

# numpy has meshgrid, 
# meshgrid uses twice memory as the result matrix but
# if used _correctly_ it's FAST

X, Y = np.meshgrid(x, y)

# numpy can avoid you explicit looping,
# but if you are so inclined...

Z2 = np.zeros((len(y), len(x)))
for r in range(len(y)):
    for c in range(len(x)):
        Z2[r, c] = z(X[r, c], Y[r, c])

# numpy has ufuncs, and
# t h i s   i s   t h e   w a y   t o   g o

Z3 = z(X, Y)

# numpy has broadcasting (it's slower than Z = z(X, Y), less memory)

Z4 = z(x, y[:,None])

# note that x is still a _row_ of numbers, indexed by _columns_,
# while y[:,None] is now a _column_ of numbers, indexed by _rows_,
# so that Z4[row,column] <-- z(x[column], y[row])

# a bit of testing

# in previous answers, Z2 (i.e., explicit loops)
# is the preferred method --- here we show that the other four
# possible methods give you exactly the same result

print np.all(Z2==Z0)
print np.all(Z2==Z1)
print np.all(Z2==Z3)
print np.all(Z2==Z4)
boffi@debian:~/Documents/tmp$ python2 grid.py 
True
True
True
True
boffi@debian:~/Documents/tmp$ 

To expand my comment above, here are some possible ways of computing a function on a grid

boffi@debian:~/Documents/tmp$ cat grid.py 
import numpy as np

def z(x,y):
  return np.sin(np.sqrt(x*x+y*y))

x = np.linspace(-1,1,11)
y = np.linspace(-2,2,21)

# naive

Z0 = np.zeros((len(y), len(x)))
for i, X in enumerate(x):
    for j, Y in enumerate(y):
        Z0[j,i] = z(X,Y)

# trampoline on a double list comprehension,
# it is possibly faster, sure it uses more memory

Z1 = np.array([[z(X,Y) for X in x] for Y in y])

# numpy has meshgrid, 
# meshgrid uses twice memory as the result matrix but
# if used _correctly_ it's FAST

X, Y = np.meshgrid(x, y)

# numpy can avoid you explicit looping,
# but if you are so inclined...

Z2 = np.zeros((len(y), len(x)))
for r in range(len(y)):
    for c in range(len(x)):
        Z2[r, c] = z(X[r, c], Y[r, c])

# numpy has ufuncs, and
# t h i s   i s   t h e   w a y   t o   g o

Z3 = z(X, Y)

# numpy has broadcasting (it's slower than Z = z(X, Y), less memory)

Z4 = z(x, y[:,None])

# note that x is still a _row_ of numbers, indexed by _columns_,
# while y[:,None] is now a _column_ of numbers, indexed by _rows_,
# so that Z4[row,column] <-- z(x[column], y[row])

# a bit of testing

# in previous answers, Z2 (i.e., explicit loops)
# is the preferred method --- here we show that the other four
# possible methods give you exactly the same result

print np.all(Z2==Z0)
print np.all(Z2==Z1)
print np.all(Z2==Z3)
print np.all(Z2==Z4)
boffi@debian:~/Documents/tmp$ python2 grid.py 
True
True
True
True
boffi@debian:~/Documents/tmp$ 
夏了南城 2024-10-27 08:03:56

归根结底:这只是安德烈·霍尔兹纳的答案的一个微小变化。如果需要的话请为他点赞!

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 之一或两者都是一维数组或列向量,它们将根据需要扩展为适当的二维数组,形成矩形网格。

To give credit where it's due: this is only a slight variation on Andre Holzner's answer. Please upvote him if you must!

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()

The syntax is perhaps easier to read with the strict minimum of array dimensions and indices. It relies on the following point (quoted from the doc).

If either or both of X and Y are 1-D arrays or column vectors, they will be expanded as needed into the appropriate 2-D arrays, making a rectangular grid.

未蓝澄海的烟 2024-10-27 08:03:55

这是一个具体的简单示例(也适用于不能采用 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() 

here's a concrete simple example (works also for functions which can't take matrix arguments for x and y):

# 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() 
纵情客 2024-10-27 08:03:55

查看 matplotlibpcolorimshow 的文档。

另一个好的起点是查看 matplotlib 库,看看是否有与您要查找的内容相匹配的绘图类型,然后使用示例代码作为您自己工作的起点:

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

Take a look at the documentation for pcolor or imshow in matplotlib.

Another good place to start is take a look at the matplotlib gallery and see if there is a plot type that matches what you are looking for and then use the sample code as a jumping off point for your own work:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文