How to plot 3D function as 2D colormap in python?

后端 未结 4 686
半阙折子戏
半阙折子戏 2020-12-30 04:30

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 scat

4条回答
  •  轮回少年
    2020-12-30 04:56

    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$ 
    

提交回复
热议问题