0

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

1 回答 1

0

所以要清楚,这行得通,但你问为什么你需要转置?

如果您查看数组的形状:

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)

很明显,要在元素方面匹配它们,您需要转换您的高度。

您对数组中哪些方向的概念是x并且y与具有的概念相反matplotlib。可能与 row-major 与 col-major 冲突有关。

于 2013-05-20T14:39:28.280 回答