Matplotlib contour array order

Question : what order determines the contour from matplotlib for the input 2D array?

Designed by . Matplotlib contour documentation says a normal call

x_axis = np.linspace(10,100,n_x) y_axis = np.linspace(10,100,n_y) matplotlib.pyplot.contour(x_axis, y_axis, scalar_field) 

Where scalar_field should be a two-dimensional array. For example, a scalar field can be generated using

 scalar_field = np.array( [(x*y) for x in x_axis for y in y_axis]) scalar_field = scalar_field.reshape(n_x, n_y) 

If a scalar field is given a contour,

 plt.contour(x_axis, y_axis,scalar_field) #incorrect 

the orientation of the graph is incorrect (rotated). To restore the correct orientation, the scalar field must be transposed:

 plt.contour(x_axis, y_axis,scalar_field.transpose()) #correct 

So, what is the order in which the contour expects the scalar field to have?

+6
source share
2 answers

You must use contour , passing in 2-D arrays for X and Y , then each point in your scalar_field array will correspond to the coordinate (x, y) in X and Y , you can conveniently create X and Y with numpy.meshgrid :

 import matplotlib.pyplot as plt import numpy as np X, Y = np.meshgrid(x_axis, y_axis, copy=False, indexing='xy') plt.contour(X, Y, scalar_field) 

The indexing argument can be changed to 'ij' if you want the X coordinate to represent the row and Y to represent the column, but in this case scalar_fied should be calculated using ij indexing.

+6
source

It is expected that x values ​​will correspond to data columns, not rows (i.e., x is the horizontal axis and y is the vertical axis). You canceled it, so you need to transpose the z values ​​to make it work.

To avoid the need for transposition, create your array as:

 scalar_field = np.array( [(x*y) for y in y_axis for x in x_axis]) scalar_field = scalar_field.reshape(n_y, n_x) 
+2
source

Source: https://habr.com/ru/post/953942/


All Articles