当前位置:网站首页>Matplotlib learning notes

Matplotlib learning notes

2022-06-13 10:16:00 Long way to go 2021

        Pyplot yes Matplotlib Sub Library of , Provided with MATLAB Similar drawings API.Pyplot The drawing module is commonly used , It is very convenient for users to draw 2D Chart .

0 preparation

         Install first matplotlib library , Enter the command at the terminal pip install matplotlib -i https://pypi.doubanio.com/simple/ download matplotlib, Then import to warehouse , And use an alias plt.

import matplotlib.pyplot as plt
import numpy as np 

1 Basic introduction

1.1 Simple drawing

         Use NumPy In the library linspace() Function to obtain 0 To 2π Between angles ndarray object .

x = np.linspace(0, math.pi*2, 100)

        ndarray Object used as a graph x The value on the axis . The following statement is used to obtain the y Displayed on axis x The corresponding sine of the angle in

y = np.sin(x)

         Use plot() Function to draw the values of two arrays .

plt.plot(x,y)

         You can set the drawing title and x and y The label of the shaft .

plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')

        show() Function call the drawing viewer window

plt.show()

Complete code :

import numpy as np
import matplotlib.pyplot as plt
import math

#  Display Chinese settings 
plt.rcParams['font.sans-serif'] = ['SimHei']        #  Replace sans-serif typeface 
plt.rcParams['axes.unicode_minus'] = False          #  Solve the problem of negative sign display of coordinate axis negative numbers 

x = np.linspace(0, math.pi*2, 100)
y = np.sin(x)
plt.plot(x, y)

plt.xlabel(' angle ')
plt.ylabel(' Sine ')
plt.title(' Sine wave ')
plt.show()

         By the code above , We can see the use of matplotlib.pyplot Modules make it easy to generate drawings quickly , But it is recommended to use an object-oriented approach , Because it can better control and customize the drawing .matplotlib.axes.Axes Most functions are also provided in the class . The main idea behind using a more formal object-oriented approach is to create graphical objects , Then just call the methods or properties of the object . This approach helps to better handle canvases with multiple drawings on them .

         In an object-oriented interface ,Pyplot For some functions only , Such as graphic creation , Users explicitly create and track drawing and axis objects . At this level , The user to use Pyplot Create graphics , Through these graphics , You can create one or more axis objects . then , These axis objects are used for most drawing operations . Yes Matplotlib Axes Class , Please read :https://www.yiibai.com/matplotlib/matplotlib_axes_class.html

         First , Create a graphic instance that provides an empty canvas .

fig = plt.figure()

         Add axis to drawing .add_axes() Method requires a 4 A list object of elements , Corresponds to the left side of the graph , Bottom , Width and height . Each number must be between 0 and 1 Between .

ax = fig.add_axes([0, 0, 1, 1])

         Set up x and y Label and title of axis

ax.set_title(' Sine wave ')
ax.set_xlabel(' angle ')
ax.set_ylabel(' Sine ')

         call axes Object's plot() Method .

ax.plot(x, y)

Complete code :

import numpy as np
import matplotlib.pyplot as plt
import math

x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)

#  Display Chinese settings 
plt.rcParams['font.sans-serif'] = ['SimHei']        #  Replace sans-serif typeface 
plt.rcParams['axes.unicode_minus'] = False          #  Solve the problem of negative sign display of coordinate axis negative numbers 


fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.set_title(' Sine wave ')
ax.set_xlabel(' angle ')
ax.set_ylabel(' Sine ')
ax.plot(x, y)
plt.show()

         reminder : In the drawing code, we often see , Useful plt., Useful ax., As for how to choose , I think simple and suitable is the best , If there are multiple subgraphs , And every subgraph needs to be decorated ,ax than plt More convenient , Otherwise use plt That's enough. .

1.2 Graphs and subgraphs

         We can't be in a blank figure Draw on , One or more must be created subplots( Subgraphs ), use add_subplot:

fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)

         This line of code means ,figure yes 2x2( There is a total of 4 Amplitude map ), And we chose 4 individual subplots( Figures from the 1 To 4) No 1 individual . If you want to create another two subgraphs , You can enter :

ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)

         We can directly in the blank subplot Draw on , Directly in the corresponding AxesSubplot Object , If input plt.plot([1.5, 3.5, -2, 1.6]) Such an order ,matplotlib Will put the picture at the last figure On the last subgraph of .

plt.plot(np.random.randn(50).cumsum(), 'k--')
_ = ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))
plt.show()

         Because creating one with multiple subplot Of figure It's a very common operation , therefore matplotlib Added a method ,plt.subplots, To simplify the process . This method will create a new figure, And return a numpy Array , It contains the created subplot object :

fig, axes = plt.subplots(2, 3)

         This operation is very useful .axes Can be indexed with a two bit data , for example ,axes[0, 1]. We can use sharex and sharey To specify different subplot Have the same x- or y-axis( In fact, it is the same range of coordinate axes ), This allows us to compare data within the same range . otherwise ,matplotlib The range of automatic drawing is not necessarily the same .

         By default ,matplotlib Will be in subplot Leave a margin between , It depends on the height and span of the drawing . So if we resize the drawing , It will automatically adjust . We can use Figure Under the object subplots_adjust Method to change the interval , Of course , You can also use the functions of the first level :

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

wspace and hspace control figure Percentage of width and length , Can be used to control subplot Spacing between . Here's an example , Let's make the interval 0:

         Notice that some labels on the shaft overlap .matplotlib Does not check whether labels overlap , So we need to directly specify the specific tick location( Mark position ) and tick labels( Mark label ), This section will be introduced later .

1.3 Color , Marker , Line style

        matplotlib Of plot The main function can accept x and y coordinate , In the options , String can specify color and line style . for example , Draw x and y, Use green dotted lines :

ax.plot(x, y, 'g--')

         This method can easily specify both color and line style ; However, some users may not like to write strings with specified colors and styles directly , Of course , We can also write more clearly :

ax.plot(x, y, linestyle='--', color='g')

         There are many color abbreviations to choose from , Of course , We can also use any color , By making hex code( Hexadecimal code , such as ’#CECECE’). By looking at plot String document , We can see all the line styles available for selection ( Direct input plot?).

         It can also be used markers( Marker ) To highlight the actual data points . because matplotlib Create a continuous line plot( Continuous line diagram ) Words , If you want to insert , It may not be clear where data points can be inserted . and marker Can be part of the style , String must be by color , Marker type , The order of styles :

plt.plot(np.random.randn(30).cumsum(), 'ko--')

         It can also be written separately :

plt.plot(np.random.randn(30).cumsum(), color='k', linestyle='dashed', marker='o')

         For a dotted line diagram , We noticed that , By default , Subsequent points are added linearly . This can be done through drawstyle To change the :

data = np.random.randn(30).cumsum()
plt.plot(data, 'ko--', label='Default')
plt.plot(data, 'g*-', drawstyle='steps-post',label='steps-post')
plt.legend(loc='best')

1.4 Mark , label , legend

         For the decoration of most drawings , There are two main ways : Use pyplot(matplotlib.pyplot) And simple, more object-oriented matplotlib API.

        pyplot The interface is designed for interactive use , It contains many methods , such as xlim, xticks, xticklabels. These methods control the extent of the plot , Mark position , Label . There are two ways to use it :

  • No parameters are passed in when calling , Use the current parameter settings ( for example ,plt.xlim() Returns the current X The scope of the shaft )
  • When calling, pass in parameters , Use the passed in parameter settings ( for example ,plt.xlim([0, 10]), Make X The axis ranges from 0 To 10)

         All these methods , Apply to active or newly created AxesSubplot On the object . Everyone is subplot There are two corresponding methods ; For example, for xlim, There is a corresponding ax.get_xlim and ax.set_xlim. Use here subplot Methods , It will be clearer .

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(1000).cumsum())

         To change x-axis tick(x Axis mark ), Use set_xticks and set_xticklabels. The former told matplotlib Along x The scope of the shaft , Where to put the mark ; By default, the location will be used as the label , But we can use set_xticklabels To set any value as a label :

ticks = ax.set_xticks([0, 250, 500, 750, 1000])
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'], rotation=30, fontsize='small')

        rotation Option to x The marking label on the shaft has a 30 The rotation of the degree of .set_xlabel to x The axis has a name , and set_title to subplot A title :

ax.set_title('My first matplotlib plot')
ax.set_xlabel('Stages')

         Use the same process to change y Axis , Put the x Turn into y.axes Class has one. set Method , Allows us to set many drawing properties at once . For the example above , We can write it as follows :

props = {
    
    'title': 'My first matplotlib plot',
    'xlabel': 'Stage'
}

ax.set(**props)

         Legend is important for drawing . There are many ways to add a legend . The easiest way is to use label Parameters :

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(30).cumsum(), 'k', label='one')
ax.plot(np.random.randn(30).cumsum(), 'k--', label='two')
plt.legend(loc='best')
plt.show()

        legend Method has some options , For example, use loc Parameter setting position . For more information , You can refer to the string documentation (ax.legend?)

        loc tell matplotlib Where to put the legend . If you're not picky , Direct setting ’best’ That's all right. , It will automatically select a suitable location . If you want to exclude one or more elements from the legend , Then don't pass it in label, Or set label='_nolegen_'.

1.5 notes

         In addition to the standard drawing type , We may want to draw our own drawing notes , Including text , Arrows or other shapes . We can add comments and text , adopt text,arrow, and annotate function .text Can be in the specified coordinates (x, y) Write the text on the , You can also set your own style :

ax.text(x, y, 'Hello world!', family='monospace', fontsize=10)

         Notes can draw text and arrows . Here's an example :

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 2 * x + 1

plt.figure(num=1, figsize=(8, 5))
plt.plot(x, y)

ax = plt.gca()  #  Set borders / Axis 

ax.spines['right'].set_color('none')    # spines It's the backbone , Four borders 
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', -0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

#  Draw a specific scatter 
x0 = 1
y0 = 2 * x0 + 1
plt.scatter(x0, y0, s=50, color='b')

# k-- Indicates the black dotted line ,k For black ,-- Said the dotted line ,lw It means line width ,  draw (x0,y0) Perpendicular to x Line of axis 
plt.plot([x0, x0], [0, y0], 'k--', lw=2.5)

'''  The parameter xycoords='data'  It means that the location is selected based on the value of the data , xytext=(+30, -30)  and  textcoords='offset points'  Description of the location of the label   and  xy  Deviation value , arrowprops Are some settings for the arrow type in the figure . '''
plt.annotate(r'$2x+1=%s$'%y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2'))

#  among -3.7, 3, Yes select text The location of ,  The space needs to use the conversion character \ ,fontdict Set text font 
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text.\mu\ \sigma_i\ \alpha_t$', fontdict={
    'size':'16', 'color':'red'})
plt.show()

1.6 Save as a file

         We can use plt.savefig To save the diagram . This method is equivalent to directly in figure Object savefig Method . for example , Want to save a SVG Version of the picture , type :

plt.savefig('figpath.svg)

         The saved file type is specified by the file name suffix . That is, if you use .pdf As a suffix , And you'll get one PDF file . Here are some important settings , Authors often print pictures :

  • dpi, Controls the resolution per inch of length
  • bbox_inches, Can be deleted figure The surrounding white space

         For example, we want to get one PNG chart , There is minimal white space ,400 DPI, type :

plt.savefig('figpath.png', dpi=400, bbox_inches='tight')

1.7 matplotlib Set up

        matplotlib Many default settings can be defined by yourself , By modifying some global settings , For example, graph size ,subplot interval , Color , font size , Grid style and so on . One way of setting is to use rc Method , for example , You want to set the global graph size to 10 x 10, type :

plt.rc('figure', figsize=(10, 10))

        rc The first parameter in is the component we want to customize , such as ’figure’, ‘axes’, ‘xtick’, ‘ytick’, ‘grid’, ‘legend’, Or others . Then add a keyword to set the new parameter . A more convenient way to write it is to write all the settings as one dict:

font_options = {'family': 'monospace',
                'weight': 'bold',
                'size'  : 'small'}
plt.rc('font', **font_options)

         For more detailed settings, see the documentation ,matplotlib Settings file under matplotlibrc, be located matplotlib/mlp-data Under the folder . If you modify this file in your own way , And put this file in the main directory , Renamed *.matplotlibrc* Words , At every startup matplotlib When , This file will be loaded automatically .


Reference resources

原网站

版权声明
本文为[Long way to go 2021]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206131010303137.html