\
♚ \
Author: Yue Xiaoshui Chang, Java, Python, Android coder.
Copy the code
\
Matplotlib profile
\
Matplotlib is a 2D graphic library that Python has transferred from Matlab. It can generate publically quality graphics on a variety of platforms in a variety of hard copy formats and interactive environments. With just a few lines of code, you can develop histogram, pie chart, scatter chart, 3D graph, etc. With strong customization and scalability. Here are some sample charts from the Matplotlib website:
\
\
\
\
And because Matplotlib is a secondary development based on NumPy (a scientific computing package) and Tkinter (a graphics framework), Matplotlib is becoming increasingly popular in the field of visualization of scientific computing results.
\
Matplotlib composition
\
Copy the code
Backend has to be said
\
Backend does the behind-the-scenes work for the drawing function in Matplotlib, and frontend refers to the drawing commands you edit. Backend can be set to adapt Matplotlib to different application scenarios, or output forms, such as: Figure pop up in Command line mode in Python, Matplotlib embedded in graphical interface tool wxPython, web application service, batch script generation of visual data, etc.
Backend can be classified into two types: an interactive integrated development environment (IDE) that includes command lines and graphical interfaces. Non-interactive, such as output image files (PNG, JPG, PDF, etc.).
Common backend types:
\
Noninteractive type | Interactive type |
---|---|
AGG: Render as a PNG file | Qt5Agg: Render using Qt5, %matplotlib Qt5 in IPython |
PS: Render as a PS file | Macosx: Render using Cocoa canvas, %matplotlib OSx can be used in Ipython |
PDF: Render as a PDF file | NbAgg: Backend used in Jupyter Notebook. %matplotlib Notebook is used in Jupyter to activate the backend |
SVG: Render as an SVG file | WXAgg: Use the wxWidgets library for rendering, %matplotlib wX in Ipython |
\
If we want to activate WXAgg render mode, we can use this
\
import matplotlib
matplotlib.use(‘WXAgg’)
\
Note that the activation statement is followed by the import statement and cannot have a plot statement such as plt.plot() in the middle
\
Matplotlib basic usage
\
As Matplotlib is a third-party library, please make sure you have Matplotlib installed on your computer.
\
There are generally two ways:
- On the CLI, enter PIP install matplotlib
- Download the WHL file for installation and refer to:
Blog.csdn.net/ygdxt/artic…
\
The import
* * * *
According to the custom of the open source community, this is the usual way to import
import matplotlib.pyplot as plt
Create a canvas
plt.figure()
If you go directly to plt.show() after plt.figure(), a blank chart canvas window pops up
The specific drawing
\
Matplotlib’s drawing is procedural-oriented, and the specific drawing operations are almost done in this step. For example, IF I want to draw sin(x) and cosine (x) in a subgraph, the control code is as follows:
\
X = np.arange(0,np.pi*2,0.01)y1 = np.sin(x)y2 = #plt.plot(x,y1,x,y2)plt.plot(x,y1)plt.plot(x,y2) plt.plot(x,y1)plt.plot(x,y2)Copy the code
\
After plt.show(), it looks like this:
\
\
The plot() function is just the simplest plotting function in the Matplotlib library. Plt.plot (x,y1,c=”y”) changes the color of sin(x) to yellow. Plt.plot (x,y1,c=”y”) changes the color of the line to yellow. You can refer to the API manual for specific requirements.
Some other important plotting functions in the Pyplot module are listed below:
\
The name of the | function |
---|---|
plt.hist() | Drawing histogram |
plt.scatter() | Draw a scatter diagram |
plt.bar() | Draw bar charts |
plt.annotate() | Annotate the image |
Note: Due to the plethora of apis in the drawing section, only the basic functions are listed here. I will create a tutorial for this section as appropriate later
According to
plt.show()
Display the entire canvas and its subgraphs.
\
\
Solve a real problem with Matplotlib
\
Suppose we now want to solve a requirement
Find the extremum of any polynomial function and visualize the results
All the code
I’ve heard that it’s better to read comments when reading code.
# -*- coding: utf-8 -*-# author: inspurer(月小水长)# pc_type lenovo# create_time: 2019/5/26 13:19# file_name: My_differ. Py# making https://github.com/inspurer# WeChat public number Num long (ID: inspurer)from sympy import *import numpy as npimport matplotlib.pyplot as pltimport mpl_toolkits.axisartist as axisartistdef count_extreme(args): # print(num_x,num_x.shape) # print(num_x,num_x.shape) # print(num_x,num_x.shape) # print(num_x,num_x.shape) # print(num_x,num_x.shape) # print(num_x,num_x.shape) # print(num_x,num_x.shape) # print(num_x,num_x.shape) # num_y = np.zeros((1,len(num_x))) num_y = np.zeros(len(num_x)) # print(num_y, num_x.shape) for item in args: Sign_y += item[0]*sign_x**item[1] num_y += item[0]*num_x**item[1] # y derivative of x dy = diff(sign_y,sign_x) # return zero of the derivative function extreme_x_list = solve(dy,sign_x) if len(extreme_x_list)==0: Return "no extrem vaule" print(extreme_x_list) # plt.figure() # axisartist.Subplot Axisartist.Subplot(FIG, 111) # Adding a drawing area object to the canvas fig.add_axes(AX) # Xy =(Max (num_x),0), xycoords='data',xytext=(0,5), xycoords='data', fontsize=16, Fontproperties ='SimHei') plt.annotate('Y ',xy =(0, Max (num_y)), xycoords='data',xytext=(5,0), textcoords='offset points', fontsize=16, Fontproperties ='SimHei') # plt.xLabel (" X-axis ", fontProperties ='SimHei',fontsize=14) Fontproperties = 'SimHei, fontsize = 14. # sympt. ylabel("Y ",fontproperties='SimHei',fontsize=14) # sympy. Title (STR (sign_y)) plt.plot(num_x,num_y) for i,extreme_x in enumerate(extreme_x_list): extreme_y = sign_y.evalf(subs={sign_x:extreme_x}) # if the slove is not real # the class is sympy,core.numbers.Zero if (isinstance(extreme_y,numbers.Zero)): Return "extreme Value is not real" p = plt.scatter(extreme_x,extreme_y,s=50,c="red") # xyText # xyCoords and textCoords specify the coordinates xy and xytext. If textCoords =None, textNone is the same as xyCoords. If neither is set, it defaults to data. # arrowprops set the shape of the arrow, Annotate ('y(%.6s)=%.6s' % (extreme_x,extreme_y), xy=(extreme_x, extreme_Y), xycoords='data', xytext=((-1)**(i+1)*30, (-1)**(i+1)*30), textcoords='offset points', fontsize=16,fontproperties='SimHei', arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2")) plt.legend(handles=[p], Labels =['points of extreme value'],loc='best') # Hide ax.axis[:].set_visible(False) Ax. axis["x"] = ax.new_floating_axis(0, Axis ["x"]. Set_axisline_style ("->", size=1.0) And combined with the arrow ax. Axis [" y "] = ax. New_floating_axis (1, 0) ax. Axis [r]. "y" set_axisline_style (" - | > ", Size =1.0) # set ax.axis["x"].set_axis_direction("top") ax.axis["y"].set_axis_direction("right") # Let's first hide all the original axes as shown above, the four sides of the rectangle. New_floating_axis (0, 0). The first 0 represents a parallel line, and the second 0 represents the line that passes through 0. Ax. axis[# "y"] = ax.new_floating_axis(1, 0); ["x"].set_axisline_style("->", size=1.0) # Ax. Axis [r]. "y" set_axisline_style (" - | > ", size = 1.0) in the # # "- | >" # is solid arrows. Finally, set the direction of the scale display on the x and y axes. For the X axis, the scale label is above or below, and for the Y axis, the scale label is left or right. Plt.grid (True) plt.grid(color='black', linestyle='--') # show()if __name__ == "__main__": plt.grid(color='black', linestyle='--') # examples # wanted: 1/3*x**3-3/2*x**2+2*x # args: [(1/3, 3), (- 3/2, 2), (2, 1)] print (count_extreme ([(1/3, 3), (- 3/2, 2), (2, 1))))Copy the code
The third-party sympy is used in the calculation of the function. Those who are interested can study first and leave a comment if they do not understand. Otherwise we can ignore it and let’s focus on the drawing
\
Where the function expression is y = 1/3*x**3-3/2*x**2+2*x as an example, only in the last line of the code according to the format can be modified. \
\
Visual result
* * * *
\
So that when we want to quickly see a complex function, the changing trends of drawings don’t need to write any code mapping can be quickly, you just need to will function according to the above format to write, and can see the function extremum points and extremum, the next step of work is the most value, the function is concave and convex function implementation.
\
Click to become a registered member of the community ** “Watching” **