SoFunction
Updated on 2024-11-10

Common ways to plot charts in Python using Matplotlib

Matplotlib is a very powerful Python graphing tool that makes it possible to visualize large amounts of data encountered in scientific calculations by drawing line graphs, scatter plots, contour plots, bar graphs, histograms, 3D graphs, and even graphical animations.

1. Basic elements

At the top of the matplotlib hierarchy is the state-machine environment provided by the module, which is used to draw image elements such as curves, text, pictures, etc. for the current dimension. The next level is the first level of the object-oriented interface, where the user can use pyplot to create and track image objects, and from there create one or more data axes that are later used for plotting.

The following shows the individual elements of the image:

Figure refers to the whole image object for containing one or more data axes (Axes), if there are no Axes, the image is empty.

fig = ()  # Create an image object
('No axes on this figure')  # Add a title
 
fig, ax_lst = (2, 2)  # Create a file that contains the2×2Images of subgraphs

Aexs is the axis (Axis) of the plural, translated as the axis system, coordinate system, can be understood as the entire image (Figure) of a sub-diagram, a graph can contain multiple sub-diagrams, we are in the sub-diagram for the drawing of specific charts. Through the () function can create a sub-figure object, through the set_title () can set the title of the sub-figure, set_xlabel (), set_ylabel () on the graph of the horizontal and vertical coordinates of the label to set.

Axis refers to a specific axis, where trick represents the scale of the axis, the location of the scale is controlled by the Location object, and the Formatter formats the string displayed by the scale, and the display of the scale can be accurately controlled by these two objects.

Artist Objects: Any element in an image can be considered an Artist, including 2D lines, text, and Axis and image Figures, which are drawn into the image when it is rendered. Most Artist objects are bound to a specific Axis, and such objects cannot be shared between Axis systems.

Matplot input data is best converted to type, using other data types such as, pandas, etc. may report an error, so convert other types via numpy before passing in parameters.

matplotlib suggests the introduction of the necessary libraries and coding is as follows, plotting first through the plt interface to create Figure object and sub-figure object ax, and then call the function plotting through ax, through the definition of the function to image drawing can avoid many repetitive operations, and easy to maintain the code. For example, the following definition of my_plotter() to complete the image plotting, passing the sub-map ax, two data data1, data2, and image plotting parameter param_dic.

import  as plt    # Introduce the necessary libraries
import numpy as np
%matplotlib inline     
 
# Define functions to perform image drawing operations
def my_plotter(ax,data1,data2,param_dic):
    (x, y,**param_dic)
 
x = (0, 10, 0.2)    # Prepare data
y = (x)
 
fig, ax = (1)    # Create subgraphs
my_plotter(ax,x, y,{ 'linestyle':'dashed','label':'sinx'})  # Calling a function to draw an image

2. Basic usage

Creating images and plotting functions

First you need to import the necessary libraries and numpy, if you are using jupyternotebook you need to add the %matplotlib inline setting to display the image.

An image is created with (), where the num attribute points to the window in which the image will be displayed, the figsize attribute allows you to specify the size of the image, and the facecolor attribute specifies the background color of the image.

Curves are drawn by (), the first two arrays of parameters are the x and y coordinates of the image. After that, the optional parameter pairs can set the color, linewidth, linestyle, and opacity of the line (alpha).

() draws a single point instead of a connected curve, again the first two arguments are arrays corresponding to the x and y coordinates of the point. The attribute s sets the size of the point, and color sets the color.

Finally output the image via () or save it as a specified image via (), note that it should be used before show(), otherwise the image will be output and thus the saved image will be empty.

If you need to draw frequently, you need to close some useless images to save memory. You can close the current Axes, () closes the current image, and () closes the current drawing window with ().

import numpy as np
import  as plt
# Set up in-line display
%matplotlib inline      
 
x = (-5, 5, 50)        # 50 numbers evenly spaced within -5 to 5
y1 = 2*x + 1                      # Define a linear function
y2 = x**2                         # Define a quadratic function
 
(num=3, figsize=(10, 5), facecolor='white')           # Create a graphic object
(x, y2, alpha=0.5)                                      # Drawing curves
(x, y1, color='red', linewidth=1.0, linestyle='--')     
([1],[1],s=200,color='orange')                       # Draw a point
 
('./')                                      # Save the picture
()                                                      # Display image
()                                                     # Close the drawing window

Adjustment of axes

By can adjust the range of the x-axis, set the name of the axis, the same with ylabel to set the y-axis. matlab can not use Chinese, you need to set the character set.

() can customize the coordinate scale by passing in the scale as an array, and can pass in a custom display of the scale values

Set the position of the axis scale: get the x-axis by axes object.xaxis and set the position by set_ticks_position() method, the available positions are: top, bottom, both, default, none, the corresponding y-axis scale are: left, right, both, default, none. none

# Set up in-line display
%matplotlib inline  
['-serif'] = ['SimHei']    # Set the character set to display Chinese
['axes.unicode_minus'] = False      # Set the negative sign to display correctly
 
x = (-5, 5, 50)        
y1 = 2*x + 1    
y2 = x**2   
 
(num=3, figsize=(10, 5))   
(x, y2)     
(x, y1, color='red', linewidth=1.0, linestyle='--')
('x-axis')                                           # Set up to display x-axis labels
(-2,2)                                              # Set the x-axis range to -2~2
([-2,-1,0,1,2])                                   # Set the x-axis scale
axes=()
.set_ticks_position('top')                        # Set the x-coordinate to be displayed in the upper border
('y-axis')
(-5,5)                                              # Set the y-axis range to -5~5
([-3,-1,0,1,3],['Low','Lower','Medium','High','Higher'])     # Customized scale values
.set_ticks_position('left')                       # set upyCoordinates are displayed in the left frame

We can also set the four borders of the image, get the axes object axes through (), get the right border through .spines['right'], after that we can set its color with set_color, and set the position of the border with set_position()

['right'].set_color('none')                      # Get and set the right frame transparent
['top'].set_color('none')
['bottom'].set_position(('data', 0))             # Place the bottom border at x=0
['left'].set_position(('data',0))                # Place the left border into they=0location

3. Legend and labeling

The label attribute can be added to define the name of the curve when using () for function plotting.

The legend is displayed in the image via (), whose loc attribute defines the position of the legend, with values 'best' : 0, 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, where best stands for the automatically assigned best position

(x, y1, label='linear')
(x, y2, color='red', linewidth=1.0, linestyle='--', label='square')
(loc='upper right')

You can also save the results of plot() as l1, l2 objects, and then pass in the handles attribute in the legend function, so that the legend function can add a legend to the specified line objects in the figure, and set the content of the legend through the labels attribute

l1, = (x, y1)
l2, = (x, y2, color='red', linewidth=1.0, linestyle='--')
# Add a legend to the specified line object
(handles=[l1,l2,], labels=['linear','square'], loc='best')

Add annotations in the picture through the () function, the first parameter is the content of the annotation, fontsize the size of the annotation, xycoords represents the position of the annotation point of the representation, data on behalf of the data according to the xy on behalf of the incoming data, textcoords = 'offset points' on behalf of the position of the annotation according to the point of the offset, xytext set the offset value, arrowprops passes the type and radian attributes of the arrow as dict.

Add text in the picture through (), the first two parameters for the position of the text, the third parameter for the text content, fontdict on the text font, color settings, ha = 'center' set center alignment, va = 'bottom' set to the bottom of its

([1],[1],s=100,color='orange')
# Add customized notes
('x²=2x-1',fontsize=20,xycoords='data',xy=(1,1),
             textcoords='offset points',xytext=(20,-30),
             arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
# Add text
(0.5,-1,"This is a text",fontdict={'size':15,'color':'green'},ha='center', va='top')

4、Drawing images Scatterplot

Scatter plot by scatter(), s attribute is the size of the point, c is the color of the point, alpha point opacity, marker specifies the shape of the point

scatterplot

n = 1024    # data size
X = (0, 1, n) # X value for each point
Y = (0, 1, n) # Y value for each point
C = np.arctan2(Y,X)           # Generate colors for each point
(X, Y, s=75, c=C, alpha=0.5, marker='o')
 
()

bar chart

Bar graphs are drawn through the () function, the first two parameters are passed an array of x positions and y values for the bars, the facecolor attribute sets the theme color, and edgecolor sets the border color

n = 10
X = (n)        # X takes 1 to 12
Y1 = ([8,9,12,6,5,10,11,13,4,2])
Y2 = ([5,6,8,3,14,10,3,2,1,4])
 
(X, Y1, facecolor='blueviolet', edgecolor='orange')
(X, -Y2)
 
# Add text labels at the top of the bar charts
for x, y in zip(X, Y1):
    (x, y , y, ha='center', va='bottom')
    
()

As shown in the figure on the right above, through the (data) you can draw a histogram of the statistical distribution of the data, the parameter bins specifies the division of statistical intervals, for the number of intervals on behalf of the division of several intervals, for the array on behalf of the specified specific intervals.

(data, bins=10)    # of intervals delineated
(data, bins=[0, 500, 1000, 1500, 2000, 2500, 3000])    # Specify specific grouping intervals

contour map

The data of the contour line is three-dimensional data, X, Y is the independent variable, Z is the dependent variable function value, according to the function value of the different display the same value as the contour line

The () function is used to fill the color, the first three parameters are the corresponding X, Y and Z values, and the cmap is the color of the fill, a color mapping scheme provided by matlabplot is used here, which maps from blue to red according to the value of the smallest to the largest.

() for contour drawing, colors='black' line color is black, linewidth=.5 line width is 0.5

Drawing text via clabel(), inline fills the text within the lines

With the colorbar() function you can add a function value to the image corresponding to the color bar

n = 256
x = (-3, 3, n)
y = (-3, 3, n)
X,Y = (x, y)     # Compile to a 256 x 256 grid and return the corresponding coordinate values to the X, Y arrays
def fun(x,y):               # Define the function value Z, a three-dimensional function elliptic paraboloid
    return x**2+y**2
 
F = (X, Y, fun(X, Y), 8, alpha=.75,cmap='RdBu')             # Perform color fills
C = (X, Y, fun(X, Y), 8, colors='black', linewidth=.5)       # Drawing contour lines
(C, inline=True, fontsize=10)                                 # Labeled text
(F)                                                         # Add a colorbar
()

three-dimensional image

Before drawing 3D graphics you need to introduce an additional package Axes3D, through which the current image is converted into a 3D graphic

Similarly 3D plots require 3D data, X and Y compiled for the grid are independent variables and Z is a function value

3D graphics are drawn by plt.plot_surface(), the attributes rstride and cstride represent the span of row and column respectively, the smaller the span, the denser the mesh on the graph, and cmap is the color matching mapping scheme for the function value

The contour plotting function () can be used to draw projections in the plane for 3D graphics. zdir='z' represents the projection along the Z-axis, so that the projection will appear in the X-Y plane, and offset represents the offset position of the projection.

 
import  as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D         # Introduce 3D mapping library
%matplotlib inline
 
fig = ()
ax = Axes3D(fig)                                # Convert the current image to 3D
 
X = (-10, 10, 0.5)
Y = (-10, 10, 0.5)
X, Y = (X, Y)            # Prepare a grid in the X-Y plane
Z = (X ** 2 + Y ** 2)        # Z-values, defined as parabolic graphs
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hsv')  # 3D mapping
(X, Y, Z, zdir='z', offset=0, cmap='hsv')        # Add a projection along the Z-axis
()

Drawing animation

Drawing animation requires an additional animation library from matplotlib.

After that, first draw the image of one of the frames, for example, here to draw the animation of sinx, first in 0 ~ 2Π take the independent variable x array, and then draw the curve of its sinx line

Then define the display function init() for the initial frame of the animation, which returns the initial line object. Then define its image display function animate for each frame, its parameter i represents the ith frame, according to i return different line object.

Finally through () to draw the image, its parameters fig for the previously created image object, init_func for the initialization of the display function, func for each frame of the display function, interval for the frequency of updates (unit ms), frames for the animation of a total of how many frames, blit for the True on behalf of each time to update only the point of change

Finally, the save() method of the returned ani object will save it as a gif, and the writer used here is imagemagick.

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation                 # Introducing animation libraries
%matplotlib inline
 
fig,ax=()                            # Create a canvas
 
x=(0,2*,0.01)                      # Take a number every 0.01 from 0 to 2Π
line,=(x,(x))                       # Draw the image of sinx
 
def init():                                      # Define the initial frame display function
    line.set_ydata((x))
    return line,
def animate(i):                                  # Define the display function for each frame
    line.set_ydata((x+i/10))
    return line,
 
# Drawing animations
ani=(fig=fig,init_func=init,func=animate,interval=20,frames=100,blit=True)
('',writer='imagemagick')        # Save the animation as a gif
 
()

5、Multi-picture

pass (a bill or inspection etc)()Can be divided into multiple subplots and select a position in them, for example, subplot(2,2,1) on behalf of the creation of a 2 × 2 subplot, and select the first subplot, you can also omit the middle comma: subplot(224) on behalf of selecting the fourth of the 2 × 2 subplots. In addition to drawing subplots directly through the plt object, subplot can return a subplot object, which can be used to draw by calling plot() through the subplot object.

import  as plt
%matplotlib inline
 
()
 
# Select the first of the 2×2 subgraphs and draw a line
(2,2,1)
([0,1],[2,3])
# Draw a line by selecting the fourth of the 2×2 subplots
ax2=(224)
([2,1],[3,4])
 
()

Note that the division here is not really splitting the image, but just assuming that the whole image is divided in order to locate the subgraphs.

For example, the following code first of all, the canvas will be considered 2 rows and 1 column to select the first block, that is, the above row of large, and then it will be considered 2 rows and 3 columns to select the fourth block, that is, the first of the second row. Through different divisions and selections can get different sizes with different locations of the subgraph. If there are conflicting areas involved, the later subgraphs will overwrite the previous subgraphs.

# Split into 2 rows and 1 column, check the first block
(2,1,1)
([0,1],[2,3])
# Split into 2 rows and 3 columns, check the fourth block.
(234)
([2,1],[3,4])

   

pass (a bill or inspection etc)subplot2grid()method can be more convenient to divide and select the subgraph, as shown below subplot2grid((3, 3), (0, 0), colspan=3) means that the picture will be divided into 3 × 3 region, starting from the 0th row and 0th column, horizontally spanning the number of columns of colspan 3, vertically spanning the number of rows of rowspan defaults to 1.

Note that you can set the title and coordinate names in a whole graph with title(), xlabel(), ylabel(), but in subgraphs you need to precede the function name with a set_

ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
([1, 2], [1, 2])    # Drawing little pictures
ax1.set_title('ax1_title')  # Set the title of the small image
 
ax2 = plt.subplot2grid((3,3), (2,1),colspan=2)
([2,1],[1,0])
ax2.set_xlabel('ax2_x')    # Set the name of the axis of the small plot
ax2.set_ylabel('ax2_y')

gridspec()function allows us to select subgraph regions as easily as using python arrays. Before use from matplotlib to introduce the module, through the Gridspec () function will be divided into regions of the image, and then return to the gs object, through the gs object can be like an array like the selection of sub-regions. For example, gs[1, :2], before the comma on behalf of the selection of the line number, if only a number represents the selection of all the line numbered 1, after the comma for the columns, here 0:2 on behalf of the selection from 0 to 2 columns before the selection of all the columns, which can be omitted from the beginning of 0. Correspondingly, the end of the guide can be omitted if it is selected, i.e. gs[1, :]. If the serial number is -2, this means that the penultimate column is selected.

import  as plt
import  as gridspec      # Introducing Libraries
%matplotlib inline
 
()
gs = (3, 3)                # Divide the image into 3 x 3 areas
ax1 = (gs[0, :])                 # Select row 0, all columns
ax2 = (gs[-1, -2])               # Select the penultimate row, the penultimate column
()

pass (a bill or inspection etc)subplots()You can create and return multiple subgraph objects at once, as shown below for the division of four subgraphs and return to ax11~ax22 four objects in turn, and the position of the four objects can not be messed up.

where sharex stands for image shared x-axis. plt.tight_layout() stands for compact display

f, ((ax11, ax12), (ax21, ax22)) = (2, 2, sharex=True, sharey=True)
([1,2], [1,2])
plt.tight_layout()
()

Picture in Picture:Through the add_axes() of the figure object can add another picture in the picture, its incoming parameters for the picture where the canvas of the four borders of the position of the proportion, return to the creation of the sub-picture object ax, using ax to draw

x=[0,1]
y=[2,3]
fig = ()
 
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])    # Create a big picture object
(x, y, 'r')                         # Big picture mapping
ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25])  # Create small pictures
(x, y, 'b')                         # Small mapping
 
()

Subchart copy: by using the twinx() function of the subchart object ax, you can copy another overlapping ax object with the same x-axis at the same position, except that the y-axis is put into a symmetric position, and finally the two subcharts will be displayed overlapped.

fig, ax1 = ()
ax2 = ()                       # Copy the ax object
 
([0,1], [2,3], 'g-')            # Drawing in the original
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')    # The y-axis of the original is on the left
([0,1], [3,2], 'b-')            # Copy the drawing in the object
ax2.set_ylabel('Y2 data', color='b')    # Copy the subplot with the y-axis on the right #
()

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.