Coloring Quiver Plot
The ax.quiver() method of matplotlib library of python provides an optional attribute color that specifies the color of the arrow. The quiver color attribute requires the dimensions the same as the position and direction arrays.
Below is the code which modifies the quiver plots we made earlier:
Example 1:
Python3
# Import libraries import numpy as np import matplotlib.pyplot as plt # Defining subplots fig, (ax1, ax2) = plt.subplots( 1 , 2 , figsize = ( 14 , 8 )) # first subplot # Creating arrows x = np.arange( 0 , 2.2 , 0.2 ) y = np.arange( 0 , 2.2 , 0.2 ) X, Y = np.meshgrid(x, y) u = np.cos(X) * Y v = np.sin(y) * Y n = - 2 # Defining color color = np.sqrt(((v - n) / 2 ) * 2 + ((u - n) / 2 ) * 2 ) # Creating plot ax1.quiver(X, Y, u, v, color, alpha = 0.8 ) ax1.xaxis.set_ticks([]) ax1.yaxis.set_ticks([]) ax1.axis([ - 0.2 , 2.3 , - 0.2 , 2.3 ]) ax1.set_aspect( 'equal' ) ax1.set_title( 'meshgrid function' ) # second subplot # Creating arrows x = np.arange( - 2 , 2.2 , 0.2 ) y = np.arange( - 2 , 2.2 , 0.2 ) X, Y = np.meshgrid(x, y) z = X * np.exp( - X * * 2 - Y * * 2 ) dx, dy = np.gradient(z) n = - 2 # Defining color color = np.sqrt(((dx - n) / 2 ) * 2 + ((dy - n) / 2 ) * 2 ) # Creating plot ax2.quiver(X, Y, dx, dy, color) ax2.xaxis.set_ticks([]) ax2.yaxis.set_ticks([]) ax2.set_aspect( 'equal' ) ax2.set_title( 'gradient' ) # show figure plt.tight_layout() plt.show() |
Output :
Example 2: Building a quiver plot of function which defines the 2D field having four vertices as shown in the below plot:
Python3
# Import libraries import numpy as np import matplotlib.pyplot as plt # Creating arrow x = np.arange( 0 , 2 * np.pi + 2 * np.pi / 20 , 2 * np.pi / 20 ) y = np.arange( 0 , 2 * np.pi + 2 * np.pi / 20 , 2 * np.pi / 20 ) X, Y = np.meshgrid(x, y) u = np.sin(X) * np.cos(Y) v = - np.cos(X) * np.sin(Y) # Defining color color = np.sqrt(((dx - n) / 2 ) * 2 + ((dy - n) / 2 ) * 2 ) # Creating plot fig, ax = plt.subplots(figsize = ( 14 , 9 )) ax.quiver(X, Y, u, v, color, alpha = 1 ) ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) ax.axis([ 0 , 2 * np.pi, 0 , 2 * np.pi]) ax.set_aspect( 'equal' ) # show plot plt.show() |
Output :
Quiver Plot in Matplotlib
Quiver plot is basically a type of 2D plot which shows vector lines as arrows. This type of plots are useful in Electrical engineers to visualize electrical potential and show stress gradients in Mechanical engineering.
Contact Us