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