Hello. Isn't ** meshgrid ** confusing? Today I will focus on ** mesh grid **. And I will play with contour, which is a method for drawing ** contour lines ** using it.
** meshgrid ** is used to create ** grid points **.
In other words, all the points in this image.A point on the coordinate plane whose x and y coordinates are both integers is called a grid point.
Now let's write the code.
import numpy as np
x = [0, 1, 2, 3]
y = [0, 1, 2, 3]
X, Y = np.meshgrid(x, y)
X and Y are as follows. Many people may think what this is ~~~~~~~~~~?!?!?!?!?!?!?!, But please do your best. Let's sort out what this means. Let's see how the first ** coordinate plane and this matrix are related **. See the image below.
how is it? Did you come a little? so. The positions of the X and Y matrices are ** matched ** with the coordinates on the plane! (Upper and lower are transposed) In other words, the upper left of the matrix is the lower left in coordinates. As you go to the lower right of the matrix, the coordinates go to the upper right.
If you know the fact that they match, the magnitudes of X and Y will be (len (y), len (x)). And len (x) * len (y) = number of grid points. Why you ask? Write it on a piece of paper first and think slowly.
Let's consider x and y with different sizes.
Thinking about X, ** X always has only 0 or 1 as an element **. Because there are only 0,1 in the array x. And if you think of 0 to 1 as one bar, you can stack 3 bars at y = 0, 100, 200. This means that you need 3 lines of [0, 1]. So the matrix of X is 3 * 2 = len (y) * len (x).
Y is the same, isn't it?
I gave a rather confusing explanation, but in a nutshell ** The size of the matrix is equal to the length x width of the grid points ** This is very easy and can prevent confusion. Even so, it's beautiful.
import numpy as np
import matplotlib.pyplot as plt
# z = 2(x + y)
def f(x, y):
return 2 * (x + y)
x = [-1, 0, 1, 2, 3]
y = [-1, 0, 1, 2, 3]
X, Y = np.meshgrid(x, y)
fig, ax = plt.subplots()
cont = ax.contour(X, Y, f(X, Y), levels=[0, 2, 4]) #Explain only here.
cont.clabel(fmt='%1.1f', fontsize=14)
plt.show()
The result is like this. In fact, if x = 2, y = -1, then z = 2 (2-1) = 2 * 1 = 2.
I will explain only * contour *. contour(X, Y, Z=f(X,Y), levels=[0, 2, 4]) First, * contour * is a tool for finding contour lines. Contour lines are the same values of Z derived from x and y. X and Y are grid points, and f (X, Y) is used to find Z at each grid point. You connect the lines along that Z. In order to know the Z at each position, we need ** grid points **. The last levels are optional, but the ones specified here will be displayed as lines.
Today I mainly wrote about meshgrid. Then I played with contour, a tool for drawing contour lines using meshgrid. meshgrid is used in many places. It is a must to understand it well. Thank you very much.
Recommended Posts