How to draw color blocks with python matplotlib imshow and pcolormesh

preface

Sometime, somewhere, the sun is bright. I clasp my fingers, lie behind my head, stretch my waist, shake my legs, and look up at the sky. It seems a little lazy. However, there was only one thought at that time, just like the poor photon that mistakenly entered the cavity of the blackbody, jumping repeatedly in my mind - "who threw the banana peel?"?

So the question comes, "how to draw color blocks in python"?

The intuitive and simple idea is to treat it as a picture and use imshow() method, that is, each picture is equivalent to an array, in which the numerical size distribution of each pixel is 0 ~ 1(float), or 0 ~ 255(uint8). Each pixel can be regarded as a color block. The color of the color block can be adjusted by changing its value.

In addition, if you are lazy, "whether there are encapsulated functions" can be called directly to complete similar operations. So based on the principle of "if you don't make a decision, ask doc for help", sure enough, after a meal of operation,

Similar cases can be found in the official website doc of matplotlib, such as pcolor, pcolormesh and pcolorfast.

This Blog is used to record the notes and summary of this exploration and learning.

imshow array is the image

Imshow is the abbreviation of image show, so pass in 2d array or RBG data to imshow(). This method can render the corresponding picture.
Here, the boundary of rendering is defined by x and y, and the 2d array z is randomly generated. The rendered color is modified in the parameter cmap 1 , you can directly pass in the name (str) or the corresponding attribute, such as PLT cm. Blues

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-1, 1.5, 0.5)
y = np.arange(-1, 1.5, 0.5)
extent = np.min(x), np.max(x), np.min(y), np.max(y)

np.random.seed(666)
z = np.random.randn(2,2)

fig, ax = plt.subplots(1,2)
ax[0].imshow(z, cmap=plt.cm.Blues, extent=extent)
ax[1].imshow(z, cmap="gray", extent=extent)
plt.subplots_adjust(wspace=0.5)
plt.xticks(x)
plt.yticks(y)

pcolor family

pcolor,pcolormesh,pcolorfast. The moment I saw these three names, I was in a trance. This "Ma what Mei"?

First of all, the common point of the three is that they can be used to draw rectangular grids.

The difference is 2:

  • For pcolor and pcolormesh, the former returns a "PolyCollection" object, while pcolormesh returns a "QuadMesh" object. In most cases (especially in the case of large arrays), the latter is more efficient, so pcolormesh is officially recommended
  • pcolorfast does not support some functions. For example, the mesh shading scheme only supports "flat", and its coordinate axis does not support log scaling.
# Arbitrarily define a function to generate a two-dimensional array
def func(x, y):
    func = np.sin(x) - np.cos(y)
    return func

x = np.arange(-1, 1.2, 0.2)
y = np.arange(-1, 1.2, 0.2)

X, Y = np.meshgrid(x, y)
Z = func(X, Y)

fig = plt.figure()
plt.pcolormesh(X, Y, Z, cmap="Blues", shading="auto")

plt.xticks(np.arange(-1, 1.5, 0.5))
plt.yticks(np.arange(-1, 1.5, 0.5))

Learn and play

Learning for application is learning. Here, slightly modify the func function above, add the time parameter, and then use animation Funcanimation function, let the mesh move. About animation For the use of funcanimation function, please refer to the official doc 3 Or my last blog, Click here, portal.

def model(t, k, w):
    x = np.arange(-1, 1.2, 0.2)
    y = np.arange(-1, 1.2, 0.2)
    X, Y = np.meshgrid(x, y)
    # Two dimensional wave function
    Z = np.sin(k*X - w*t) - np.cos(k*Y - w*t)

    im = plt.pcolormesh(X, Y, Z, cmap="Blues", shading="auto")
    return im

# Set initial value
k = 0.2
w = 0.8
t = np.linspace(0, 5, 20)

fig, ax = plt.subplots()
ani = animation.FuncAnimation(fig, model, frames=t, fargs=(k, w))

plt.title("pcolormesh")
plt.xticks(np.arange(-1, 1.5, 0.5))
plt.yticks(np.arange(-1, 1.5, 0.5))

ani.save('colorBlocks.gif',writer='pillow')

summary

Today, out of curiosity, I learned some grid drawing methods, especially imshow and pcolormesh. At the same time, a two-dimensional wave function is defined to make the grid move, which is also very interesting.
In addition, can a new brain hole be made into a 3D version, similar to the effect of movable type printing animation at the Olympic opening ceremony.

  1. https://matplotlib.org/stable/gallery/color/colormap_reference.html#sphx-glr-gallery-color-colormap-reference-py ↩︎

  2. https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.pcolormesh.html#differences-pcolor-pcolormesh ↩︎

  3. https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html ↩︎

Tags: Python

Posted by interpim on Wed, 04 May 2022 16:47:31 +0300