简体   繁体   中英

Matplotlib surface plot of precomputed values

I trying to plot a grid of values obtained via finite differencing. Hence all the examples which show me how to make a mesh-grid output xx, yy then feed these into f to generate a grid-evaluation f(xx, yy) won't work.

If I were to plug in the grid, as I filled it in as in the example below, I am required to transpose my grid in order for it to work. This doesn't make any sense to me. Could someone explain please?

# Calculations

import itertools
import numpy

x_array = numpy.linspace(0, 1, 5)
y_array = numpy.linspace(0, 3, 20)

num_x = len(x_array)
num_y = len(y_array)

heights = numpy.zeros((num_x, num_y))
for x, y in itertools.product(xrange(num_x), xrange(num_y)):
    heights[x, y] = numpy.random.normal() + x + y
    # actual usage is a complicated finite difference scheme, so cannot be made explicit in terms of x & y

# Plotting

import matplotlib; matplotlib.use("Qt4Agg")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
x_mesh, y_mesh = numpy.meshgrid(x_array, y_array)
try:
    ax = fig.add_subplot(211)
    ax.pcolor(x_mesh, y_mesh, heights)
except ValueError as E:
    print "Error:", E
try:
    ax = fig.add_subplot(211)
    ax.pcolor(x_mesh, y_mesh, heights.T)
    ax = fig.add_subplot(212, projection="3d")
    ax.plot_surface(x_mesh, y_mesh, heights.T, cmap=matplotlib.cm.coolwarm)
    colorbar = matplotlib.cm.ScalarMappable(cmap=matplotlib.cm.coolwarm)
    colorbar.set_array(heights)
    fig.colorbar(colorbar)
    print "No problems, but why should heights be transposed??"
except Exception as E:
    print "Error:", E
plt.show()

so to be clear, this works but you are asking why you need the transpose?

If you look at the shape of your arrays:

In [75]: x_mesh.shape
Out[75]: (20, 5)

In [76]: y_mesh.shape
Out[76]: (20, 5)

In [77]: heights.shape
Out[77]: (5, 20)

It is clear that to match them up element-wise you need to transpose your heights.

Your notion of which directions in the array is x and y is opposite of the notion that matplotlib has. Likely related to a row-major vs col-major conflict.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM