当前位置:网站首页>Matplotlib quick start

Matplotlib quick start

2022-07-07 22:26:00 51CTO

Matplotlib What is it? ?

Matplotlib Is a comprehensive library , Used in Python Create static , Animated and interactive visual images .

at present (22 year 6 month ) The latest stable version is 3.5.2

install :

Use pip Installation

​pip install matplotlib​

Quick start

Let's first import matplotlib

      
      
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np # use numpy Generate the data , Demonstrate as an example .
  • 1.
  • 2.
  • 3.

Matplotlib In the figure (Figure)( for example , window ,Jupyter Small parts, etc ) Draw data on , A graph can contain one or more axis fields (Axes).

Axes It can be based on x-y Coordinates the drawing area of the specified point ( Or in polar coordinates θ-r,3D In the picture x-y-z etc. ). Create with Axes The easiest way to get a graph of is to use  ​ ​pyplot.subplots​​​. then , We can use ​ ​Axes.plot​​ stay Axes Draw some data on :

      
      
x = [1,2,3,4]
y = [1,4,3,2]
fig,ax = plt.subplots() # Create a diagram fig, The default includes a axes
ax.plot(x,y) # draw x-y Line chart of
plt.show() # Show the drawing . Please note that , If you use save Save the picture , Need to be in show Save before
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

The line chart will be displayed after running :

Matplotlib Quick start _ Broken line diagram

chart (Figure) Structure

A picture has the following parts : title (Title)、 legend (Legend)、x、y Axis labels (xlabel、ylabel) wait ......

Matplotlib Quick start _Python_02

The following is a part by part introduction .

chart Figure

Complete image . This graph tracks all sub axis domains (Axes)---- A group of “ special ” Painting ( title , legend , Color bar, etc ), Even nested subgraphs .

The easiest way to create a new diagram is to use pyplot:

      
      
fig = plt.figure() # Empty graph , No, Axes
fig, ax = plt.subplots() # Yes 1 individual Axes
fig, axs = plt.subplots(2, 2) # Yes 2x2( Two lines and two columns ) individual Axes
  • 1.
  • 2.
  • 3.

Usually , Set the axis field (Axes) And Figure It is convenient to create together , But you can also add the axis domain manually later .

Axis domain Axes

Axis domain (Axes) Is attached to the graph (Figure) On , Contains graphics for plotting data .

It usually includes two shafts (Axis) object . The two axes provide scales (ticks) And labels (tick label), To provide a scale for the data in the axis . Every ​ ​ Axis domain ​​​ There's also a title ( adopt  ​ ​set_title())​​​ Set up )、 One x label ( adopt  ​ ​set_xlabel())​​​  Set up ) And a y label ( adopt  ​ ​set_ylabel())​​  Set up ).

 ​Axes​​​  Class and its member functions use the OOP The main entry point of the interface , And most drawing methods are defined on it ( for example , As shown above , Use ​ ​plot​​​ Method )​​ax.plot()​

Axis Axis

Axis setting scale (scale) And limits (limits) And generate scales (ticks, Mark on shaft ) And scale labels (ticklabels, String marking the scale )ticks The position is determined by the positioner (Locator) determine ,ticklabel The string consists of ​ ​ Formatter (Formatter)​​​ Set up . Correct ​ ​ positioner (Locator)​​​ and ​ ​ Formatter (Formatter)​​ The combination of can control the scale position and label very finely .

Artist

Artist Here it is translated into an artist or painter .

Basically , Everything visible on the graph is an artist ( Even ​ ​ graphics ​​​,​ ​ Axis domain ​​​ and ​ ​ Axis ​​​ object ). This includes ​ ​ Text ​​​、​ ​Line2D​​​ 、​ ​ aggregate ​​​、​ ​Patch​​ etc. . When rendering graphics , All artists will be drawn to canvas On . Most artists are associated with axis fields ; Such artists cannot be shared by multiple axis fields , Nor can it move from one axis to another .

Input data type of drawing function

Drawing function receives ​​numpy.array​​​ or ​​numpy.ma.masked_array​​​ As input , Or it can be passed to ​​numpy.asarray​​​ The data of .pandas Data or ​​numpy.matrix​​​ May not work properly . A common convention is to convert data into ​​numpy.array​​. for example :

      
      
b = np.matrix([[1, 2], [3, 4]])
b_asarray = np.asarray(b) # Use np.asarray() Convert it to np.array type
  • 1.
  • 2.

Most methods can also resolve addressable objects , Such as ​​dict​​​,​​np.recarray​​​ or ​​pandas.DataFrame​​.

Matplotlib Allow the use of keyword parameters to generate images , Transfer and x,y Corresponding string .

      
      
np.random.seed(19680801) # seed the random number generator.
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

fig, axes = plt.subplots(2,1) # fig Have 2 That's ok 1 List subgraphs , Store in axes Array (np.array type ) in .
ax = axes[0]

ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set_xlabel('entry a')
ax.set_ylabel('entry b')
# Axis domain 2 , Remove the color c, shape s Parameters .
ax2 = axes[1]
ax2.scatter('a', 'b', data=data)
plt.show()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

The drawing is , The second one is that s,c Image after parameter :

Matplotlib Quick start _Python_03

Encoding style Coding Styles

object-oriented (OO) and pyplot The function interface .

Basically, there are two uses Matplotlib Methods :

  • Create explicitly “ graphics (Figures)” and “ Axis domain (Axes)”, And call the method on it (“ object-oriented (OO) style ”).
  • rely on pyplot Automatically create and manage drawings and axes , And use pyplot Function to plot .

Use OO style ( I feel OO The style is better , Just in the axis field (Axes) Object can be set , Very clear ):

      
      
x = np.linspace(0, 2, 100) # Generate some data

# Use OO style , First generate two objects Graph and axis field (fig, ax)
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
# call ax Object method
ax.plot(x, x, label='linear') # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic') # Plot more data on the axes...
ax.plot(x, x**3, label='cubic') # ... and some more.
ax.set_xlabel('x label') # Add an x-label to the axes.
ax.set_ylabel('y label') # Add a y-label to the axes.
ax.set_title("Simple Plot") # Add a title to the axes.
ax.legend() # Add a legend.
plt.show() a legend.
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

Or use pyplot Function style :

      
      
x = np.linspace(0, 2, 100) # Sample data.

plt.figure(figsize=(5, 2.7), layout='constrained')
plt.plot(x, x, label='linear') # Plot some data on the (implicit) axes.
plt.plot(x, x**2, label='quadratic') # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.


Matplotlib Quick start _Matplotlib_04

( Besides , There's a third way , Used in GUI Embed... In the application Matplotlib The situation of , Even for graphic creation . For more information , See the corresponding section in the Library :​ ​ Embed Matplotlib​​.

Common drawing types

From the homepage of the official website Get into ​​Plot types​​, You can see how to draw commonly used different types of graphs .

Matplotlib Quick start _ data _05



You can see , Common line chart 、 Scatter plot 、 Histogram, etc . Click the corresponding figure to enter the corresponding case .

Matplotlib Quick start _Python_06


The main usage is basically like this , We'll talk about some style adjustments later .


Reference resources :

 ​Matplotlib documentation — Matplotlib 3.5.2 documentation​

​https://matplotlib.org/stable/index.html​

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207072135076271.html