python——detailed explanation of usage of matplotlib

Table of contents

1. Introduction to matplotlib

1.1 Configuration through configuration files

3.2 Configure through rcParams['param_name']

3.3 Configuration through matplotlib.rc() function

2. Draw simple graphics with matplotlib

2.1 Drawing using plt.subplots

2.2 Structure of Figure

2.2.1 Figure Figure

2.2.2 Axes

2.2.3 Axis

2.2.4 Artist

2.2.5 Input data types of drawing functions

2.2.6 Coding Styles, object-oriented (OO) and pyplot function interface


1. Introduction to matplotlib

MatplotlibIt is Pythonan important part of the ecosystem and is a drawing library for visualization. It provides a complete set of similar matlabcommands APIand visualization interfaces that can produce beautiful graphics at a publication quality level, Matplotlibmaking drawing very simple and in terms of ease of use. An excellent balance between performance and performance.

After successful installation, you can Pythonimport and use it in like other libraries Matplotlibwithout the need to configure more files. Usually we use aliases after importing them mpl:

import matplotlib as mpl

MatplotlibThe configuration is more used to modify the default style of drawing graphics. MatplotlibThe configuration file contains various default graphics configuration information. We can customize the style of the drawn graphics by modifying these configuration information and modifying the global parameters. These parameters can Change graphic size, color scheme, fonts and a series of other information. Drawing configuration can be completed in multiple ways Matplotlib. The following three configuration methods are introduced: 配置文件configuration, rcParams['param_name']dynamic configuration and matplotlib.rc()function configuration.

1.1 Configuration through configuration files

Configuration files can also be divided into several different levels. If we want to modify the default configuration used by all graphics, we need to modify the global default configuration; and if we need to use different configurations according to different tasks, or different users use different configurations , you need to modify the local configuration file to be able to use different graphics configurations for different users and tasks. According to the scope of the configuration file, it can be divided into three levels: global configuration file, user-level configuration file and current task configuration file. The three-level files of different systems are located in different directories. You can view the path of the configuration file by using the following code:

import matplotlib as mpl
import os
​
# 全局配置目录
print(mpl.__path__)
# 当前用户配置目录
print(mpl.get_configdir())
# 当前任务配置目录,即当前代码运行目录
print(os.getcwd())

  • The global configuration file mpl-data\matplotlibrcis located in Matplotlibthe installation directory of . For example, Windowif it is installed in D:\Program Files\Python39\lib\site-packages\matplotlibthe directory, the full file name of the global configuration file is D:\Program Files\Python39\lib\site-packages\matplotlib\mpl-data\matplotlibrc. By default, graphics are drawn using this configuration file.

  • The user-level configuration file .matplotlib\matplotlibrcis located under the user directory. For example, if the user directory is C:\Users\Brainiac\, then the corresponding configuration file is C:\Users\Brainiac\.matplotlib\matplotlibc; if this file does not exist, it can also be created and modified according to the global configuration file and user needs.

  • The current task configuration file matplotlibrc, which is located under the code running directory, can be used to customize the configuration for the current task code. MatplotlibThis file does not exist by default, that is, the global or current user configuration file is used by default. We can create this file as needed. and configure it as needed.

3.2 Configure through rcParams['param_name']

If you just want to simply modify the custom configuration in the current file, you can rcParams['param_name']modify it more quickly. You can see what properties can be customized by using the following code:

print(mpl.rc_params())
print(mpl.rcParamsDefault)
print(mpl.rcParams)
  1. mpl.rc_params(): This method returns a dictionary containing the current matplotlib runtime configuration parameters. These configuration parameters include default colors of graphic elements, line styles, font settings, axis configurations, and more. By looking at these parameters, you can understand the current matplotlib configuration to better understand how the graph is drawn and styled.

  2. mpl.rcParamsDefault: This property returns the default runtime configuration parameters for matplotlib. These default configuration parameters are preset values ​​when the matplotlib library is installed. If you want to restore matplotlib's default settings, you can reset it with these default parameters.

  3. mpl.rcParams: This property contains the current runtime configuration parameters of matplotlib and represents the current matplotlib configuration. You can customize the display and style of the graph at runtime by modifying these parameters. For example, the graph's default colors, line styles, font settings, axis configurations, and more can be modified to meet specific needs and aesthetic requirements.

rcParams['param_name']The way to modify the configuration using the method is as follows, where param_namerepresents the attribute name:

Example:

mpl.rcParams['lines.linewidth'] = 2
# 修改线条颜色为红色
mpl.rcParams['lines.color'] = 'r'

In practical applications, the two most commonly used configurations include the display of Chinese and Chinese negative signs. If no configuration is performed, the display of Chinese and Chinese negative signs is not supported by default:

#显示中文
mpl.rcParams['font.sans-serif'] = ['SimHei']
#显示负号
mpl.rcParams['axes.unicode_minus']=False

3.3 Configuration through matplotlib.rc() function

Similarly, we can also use matplotlib.rc()the function for configuration. The usage method is as follows:

# 修改线宽
mpl.rc('lines', linewidth=2, color='g')

The rcfirst parameter of the function is groupIndicates the group to which the attribute belongs, which is used to limit the scope of the attribute. For example, in the above example, the line width linewidthbelongs to the line lines. It is used to limit it to only work in lines, but linewidthnot to line widths such as coordinate axes. , if you want to modify the graphic line width including the coordinate axes linewidth, you need to use:

# 修改整个图形线宽
mpl.rc('axes', linewidth=2)

2. Draw simple graphics with matplotlib

Matplotlib plots data on a figure (for example, window, Jupyter widget, etc.), which can contain one or more axes.

2.1 Drawing using plt.subplots

Axes is a drawing area where points can be specified based on their xy coordinates (or theta-r in polar plots, xyz in 3D plots, etc.). The easiest way to create plots with Axes is to use pyplot.subplots . Then, you can use Axes.plot to plot some data on Axes:

For example:

x = np.arange(-10,11)
y = x**2 -2*x + 9
fig,ax = plt.subplots() # 创建一个图fig, 默认包含一个axes
ax.plot(x,y) # 绘制x-y的折线图
plt.show()  # 显示绘制的图。请注意,如果使用save保存图片,需要在show前面保存

 

2.2 Structure of Figure

A picture has the following parts: title, legend, x, y axis labels (xlabel, ylabel), etc. The schematic diagram is as follows:

 

2.2.1 Figure Figure

Complete image. The plot keeps track of all sub-axes - a set of "special" plots (titles, legends, color bars, etc.), even nested sub-plots.

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

fig = plt.figure()  # 空图,没有Axes
fig, ax = plt.subplots()  #有1个Axes
fig, axs = plt.subplots(2, 2)  # 有2x2(两行两列) 个Axes

Usually, it is convenient to create the Axes together with the Figure, or you can add the Axes manually later.

2.2.2 Axes

Axes are attached to the Figure and contain the graphics used to plot the data.

Usually includes two axis (Axis) objects. The two axes provide ticks and tick labels respectively to provide scale for the data in the axis. Each axis also has a title (set via set_title() ), an x ​​label (set via set_xlabel() ), and a y label (set via set_ylabel()) ).

The Axes class and its member functions are the main entry point for using the OOP interface, and most drawing methods are defined on itax.plot()

2.2.3 Axis

The axis sets the scale and limits and generates ticks (marks on the axis) and tick labels (ticklabels, strings marking the ticks). The ticks position is determined by the locator (Locator), and the ticklabel string is determined by the formatter . (Formatter) settings. The right combination of Locators and Formatters can provide very fine control over tick positions and labels.

2.2.4 Artist

rtist here is translated as artist or painter.

Basically, everything visible on the graph is an artist (even the graph , axes , and axis objects). This includes text , Line2D , collections , patches , etc. When rendering a graph, all artists will be drawn to the canvas . Most artists are associated with an axis; such an artist cannot be shared by multiple axes, nor can it be moved from one axis to another.

2.2.5 Input data types of drawing functions

Drawing functions receive numpy.arrayeither numpy.ma.masked_arrayas input, or numpy.asarraydata that can be passed to. pandas data numpy.matrixmay not work properly. A common convention is to convert the data to before plotting numpy.array, example:

b = np.matrix([[1, 2], [3, 4]])
b_asarray = np.asarray(b) # 使用np.asarray()将其转换成np.array类型

Most methods can also resolve addressable objects such as dict, np.recarrayor pandas.DataFrame.

Matplotlib allows you to generate images using keyword arguments, passing strings corresponding to x and y:

The scatter method is usually a function provided by a data visualization library (such as Matplotlib or Seaborn) for plotting scatter plots:

Parameters and usage of scatter method in Matplotlib:

matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None)

Parameter explanation:

  • x: Abscissa data, which is an array or Series used to represent the abscissa position of each point in the scatter plot.

  • y: Vertical coordinate data, which is an array or Series used to represent the vertical coordinate position of each point in the scatter plot.

  • s: The size of the points, which can be a numerical value or an array, controls the size of the scatter points. The default value is None, which means use the default point size.

  • c: The color of the point, which can be a color string, color list or array, used to control the color of the scatter points. The default value is None, which means use the default color.

  • marker: The mark style of the point, which can be a mark string, for example, 'o' means dot, 's' means square, etc. The default value is None, meaning the default markup style is used.

  • cmap: Colormap object or string used to specify color mapping. It is used when specifying the c parameter as a numerical value to map the numerical value to the color space. The default value is None, which means use the default color map.

  • norm: Normalize object used to normalize data. It is used when specifying the c parameter as a numeric value. The default value is None, which means the default normalization method is used.

  • vminand vmax: used to set the minimum and maximum values ​​​​of the color map range. They are used when specifying the c parameter as a numeric value. The default value is None, which means using the minimum and maximum values ​​of the data as the range.

  • alpha: The transparency of the point, the value range is [0, 1], where 0 means completely transparent and 1 means completely opaque. The default value is None, which means use the default transparency.

  • linewidths: The width of the point boundary, used to control the width of the boundary line of the point. The default value is None, which means the default line width is used.

  • edgecolors: The color of the point boundary, used to control the color of the boundary line of the point. The default value is None, which means use the default color.

Example:

np.random.seed(19680801)  # 伪随机数
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 拥有2行1列个子图,存放在axes数组(np.array类型)中。
print(axes)
ax = axes[0]
​
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set_xlabel('entry a')
ax.set_ylabel('entry b')
# 轴域2 ,去掉颜色c,形状s参数。
ax2 = axes[1]
ax2.scatter('a', 'b', data=data)
plt.show()

ax.scatter('a', 'b', c='c', s='d', data=data) is expressed as follows:

  1. 'a', 'b'`: This is the data of the horizontal axis and the vertical axis. 'a' represents the horizontal axis data, and 'b' represents the vertical axis data. In this example, 'a' and 'b' are both numpy arrays containing 50 data points, used to draw the abscissa and ordinate of the scatter plot.

  2. c='c': This is to set the color parameters of scatter points. Here, 'c' stands for color, meaning the color of each scatter point will be data['c']determined by the data in . data['c']is a numpy array containing 50 random integers that will assign a color to each data point.

  3. s='d': This is the parameter that sets the size of the scatter points. Here, 'd' stands for size, meaning the size of each scatter point will be data['d']determined by the data in . data['d']is a numpy array containing 50 random floats, which will be of a specified size for each data point.

  4. data=data: This parameter tells scatterthe function datato get the 'x' and 'y' axis data (i.e. 'a' and 'b'), as well as the color and size parameters ('c' and 'd') from the dictionary.

 

2.2.6 Coding Styles, object-oriented (OO) and pyplot function interface

There are basically two ways to use Matplotlib:

  • Explicitly create Figures and Axes and call methods on them (Object-Oriented (OO) style).

  • Rely on pyplot to automatically create and manage figures and axes, and use pyplot functions for plotting.

Using the OO style, I think the OO style is better. You only need to set it on the Axes object. It is very clear. Example:

plt.subplots()Is a function in the Matplotlib library used to create subplots. It can create a graph containing multiple subgraphs at one time and store these subgraphs in a NumPy array (np.array type), making it more convenient to manage and operate multiple subgraphs.

plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
  • nrows: Indicates the number of rows of the subgraph, that is, how many rows of subgraphs are in the graph.

  • ncols: Indicates the number of columns of the subgraph, that is, how many columns of subgraphs are in the graph.

  • sharex: If set to True, all subplots will share the same x-axis (i.e. abscissa). The default value is False, which means each subplot has an independent x-axis.

  • sharey: If set to True, all subplots will share the same y-axis (i.e. vertical coordinate). The default value is False, which means each subplot has an independent y-axis.

  • squeeze: If set to True, when the number of rows or columns is 1, the returned subplot array will be compressed. If set to False, the returned subplot array is a two-dimensional array regardless of the number of rows and columns. The default value is True.

  • subplot_kw: is a dictionary of configuration parameters passed to each subgraph. For example, you can use this parameter to set properties such as titles, axis labels, etc.

  • gridspec_kw: is a dictionary of configuration parameters passed to GridSpecthe object. GridSpecUsed to arrange subplots more flexibly and can be used to create irregular subplot layouts.

  • **fig_kw: Here are the other keyword arguments fig_kwpassed to . Is a function that creates graphics. You can use parameters to set the properties of the graphics, such as graphic size, title, etc.plt.figure()plt.figure()fig_kw

x = np.linspace(0, 2, 100)  # 产生一些数据
​
# 使用OO风格,先产生两个对象 图和轴域 (fig, ax)
fig, ax = plt.subplots(figsize=(5, 5), layout='constrained')
# 调用ax对象的方法
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()

In this code, fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')there are statements to create graphics and subplots using Matplotlib. Let me explain what each parameter means:

  1. figsize=(5, 2.7): This is the parameter used to set the size of the graph. figsizeIs a tuple containing two elements, representing the width and height of the graphic (in inches). Here, set the width of the graphic to 5 inches and the height to 2.7 inches.

  2. layout='constrained': This is a very special parameter that has no directly defined meaning in Matplotlib. In fact, this parameter is not a standard parameter in Matplotlib, so in this specific code snippet, layout='constrained'it may not be interpreted correctly or have the expected effect.

In Matplotlib, plt.subplots()function layoutparameters do not exist. plt.subplots()Among the parameters of the function, there is no layoutparameter named. If you want to control the layout and arrangement of subgraphs, you can use plt.subplot()or plt.GridSpec()and other functions to perform more advanced subgraph positioning and layout settings.

Use pyplot function style:

x = np.linspace(0, 2, 100)  # 产生一些数据
plt.figure(figsize=(5, 5), 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()
plt.show()

 

Guess you like

Origin blog.csdn.net/longhaierwd/article/details/131908379