An article to learn Matplotlib

An article to learn Matplotlib

Introduction

This article explains the basic grammar of Matplotlib through a large number of cases.

grammar

The following is common syntax for Matplotlib:

  • Import library:import matplotlib.pyplot as plt

  • drawing:plt.plot(x, y)

    • xand yare lists or arrays of numbers specifying the horizontal and vertical coordinate values ​​of the data points.
  • Show the plot:plt.show()

  • Add labels, title and axes:

    • plt.xlabel('X Label')
    • plt.ylabel('Y Label')
    • plt.title('Title')
  • Custom styles:

    • Line Color: 'r'(Red), 'g'(Green), 'b'(Blue)
    • Point markers: 'o'(circle), '^'(pointing triangle), 's'(square)
    • Line type: '-'(solid line), '--'(dashed line)
    • Line width:linewidth=3
    • Mark size:markersize=12
  • Define a subgraph:

    • Build the grid:fig, axs = plt.subplots(rows, cols)
    • Access subgraphs:axs[row][col]
    • Set the subplot title:axs[row][col].set_title('Title')
    • Plotting in subplots: 'axs[row][col].plot(x, y)' or axs[row][col].bar(x, y)etc.
  • Save image to file:plt.savefig('file_name.png', dpi=300, bbox_inches='tight')

    • dpiDefines the number of pixels per inch.
    • bbox_inchesOption to choose a "tight" or "loose" layout
  • Other commonly used:

    • plt.grid(True)add grid
    • plt.legend()add legend
    • plt.xticks()Set the position of the x-axis scale
    • plt.yticks()Set the position of the y-axis scale
    • plt.xlim()Set the x-axis coordinate range
    • plt.ylim()Set the y-axis coordinate range
    • plt.subplots_adjust()Adjust the spacing and margins between subplots.
    • Here are more Matplotlib syntax and details:
  • Three-dimensional plotting: There are also many functions in Matplotlib for creating 3D graphics, the most common of which is the use of the mplot3d toolkit. The imported package name is still "mpl_toolkits.mplot3d", and plt.subplots()an projection="3d"argument can be specified in the function to convert the axes to 3D.

  • Data normalization: In some cases, data needs to be normalized or visualized. Matplotlib provides some convenient and fast APIs to help you accomplish this task. For example, automatically normalize data through functions such as plt.hist()or .plt.boxplot()

  • Support mathematical expressions: Matplotlib can support mathematical expressions written in Latex, just add a "$" before the text string.

  • Embedding charts into GUI applications: Embedding Matplotlib charts into Python GUI applications is a common use case. This can be achieved through the built-in Matplotlib interactive API in GUI toolkits such as PyQt, Tkinter, and wxPython.

  • Specify the plot style: In addition to the style options listed above, Matplotlib provides many other adjustable properties, such as background color, grid line width and padding, etc. matplotlibrcCustom styles can be specified through definition files or dynamic configuration options. These properties can also be directly accessed and set or changed in Python scripts for specific graphics components.

  • Multi-line text on subplots: Sometimes it is necessary to add multi-line annotations or labels, and Matplotlib can support using the text() function on subplots to achieve similar annotation purposes.

explain

Draw a line chart

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]

plt.plot(x, y)  # 在坐标轴上绘制线条
plt.xlabel('X Label')  # 添加x轴标签
plt.ylabel('Y Label')  # 添加y轴标签
plt.title('Line Chart Example')  # 添加标题
plt.show()  # 显示图形

This example demonstrates how to draw a line chart using Matplotlib. The lists xand ycontain the horizontal and vertical coordinate data, respectively, and plt.plot()connect them using a function to draw the line. Adding titles, axis labels, and tick labels can improve chart readability.

draw histogram

import matplotlib.pyplot as plt  #导入Matplotlib模块

x = ['A', 'B', 'C', 'D', 'E']  #定义横轴刻度标签
y = [10, 8, 6, 4, 2]  #定义纵轴数据值

plt.bar(x, y, width=0.5, align='center', color=['red', 'blue', 'green', 'purple', 'orange'])  #调用bar()函数创建柱状图,并指定参数
# 参数width为柱宽,默认为0.8;参数align为柱在标记上的对齐方式,默认为'edge'
# 在本例中,设置了柱的宽为0.5并居中对齐,同时也指定了每个条形的颜色。

plt.xlabel('Categories')  #添加x轴标题
plt.ylabel('Values')  #添加y轴标题
plt.title('Bar Chart Example')  #设置图表标题
plt.show()  #显示图表

This example demonstrates how to draw a vertical histogram. xContains horizontal labels (categories), while yvertical values ​​are contained. plt.bar()Functions are used to draw them, and a number of styling options are provided, such as 'width', 'align' and 'color'.

Draw a scatterplot

import matplotlib.pyplot as plt  #导入Matplotlib模块

x = [1, 2, 3, 4, 5]  #定义x轴数据
y = [10, 8, 6, 4, 2]  #定义y轴数据
colors = ['red', 'green', 'yellow', 'blue', 'purple']  #定义散点的颜色列表

plt.scatter(x, y, s=100, c=colors, marker='o', alpha=0.5)  
#调用scatter()函数创建散点图,并指定参数
# 参数s为散点的大小,默认为20;参数c为每个点的颜色;参数marker指定每个点形状(在此为圆);alpha参数设置点的透明度。

plt.xlabel('X Label')  #添加x轴标签
plt.ylabel('Y Label')  #添加y轴标签
plt.title('Scatter Plot Example')  #添加标题

plt.show()  #显示图表

This example demonstrates how to draw a simple scatterplot. The list sum xcontains ythe horizontal and vertical coordinate data, while the colors list defines the colors used for each data point. Use plt.scatter()functions to determine style parameters such as point size and shape, and adjust point transparency via the alpha parameter.

draw pie chart

import matplotlib.pyplot as plt  #导入Matplotlib模块

labels = ['A', 'B', 'C', 'D']  #定义标签labels
data = [30, 20, 10, 40]  #定义数据
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']  #定义饼图显示区域颜色

plt.pie(data, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)  
#调用pie()函数创建饼图,并指定参数
# 参数labels为饼图中各部分的标签;参数colors给出了用于稳定饼图底色的四种颜色.
# 自动百分比句型说明每个区域占用的百分比;startangle指定旋转图表的起始角度。

plt.title('Pie Chart Example')  #设置图表标题
plt.show()  #显示图表

This example demonstrates how to draw a simple pie chart. plt.pie()The function is used to plot it, with the data list 'data' and the automatic label generator 'labels' in the parameters. Some other options such as colors ('colors'), raft ('startangle'), and value display format ('autopct') are also described.

Draw a heat map

import numpy as np
import matplotlib.pyplot as plt

data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])  #用numpy模块创建一个3x3的矩阵并赋值

heatmap = plt.pcolor(data, cmap=plt.cm.Blues)  #调用pcolor()方法为数据生成颜色热图,并传入自定义配色和颜色比例尺。
plt.colorbar()   #调用colorbar()方法给图表添加颜色条。

plt.xticks(np.arange(0.5, len(['A', 'B', 'C']) + 0.5), ['A', 'B', 'C'])  #设定x轴刻度、标签和范围
plt.yticks(np.arange(0.5, len(['D', 'E', 'F']) + 0.5), ['D', 'E', 'F'])  #设定y轴刻度、标签和范围

plt.title('Heatmap Example')  #设置图表标题
plt.show()  #显示图表

This example demonstrates how to draw a heatmap. A two-dimensional NumPy array datastores the data, and the 'plt.pcolor()' function is used to create the matrix colormap. Adjust the position of the ticks by adding xticks()the yticks()sum function and using the value range (0.5-len+0.5). On top of this it also shows how to add legend labels (using plt.colorbar()a function to call the detailed colorbar).

Draw 3D graphics

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

# 定义一个新的3D坐标系
fig = plt.figure()  #生成一张新的图片
ax = fig.add_subplot(111, projection='3d')  #在其中增加一个子图,projection='3d'参数告诉Matplotlib要创建3D图像

# 生成X、Y的等间隔数字,并根据它们的组合生成Z
x = np.linspace(-1, 1, 100)  # 生成等间隔数字-1到1,共100个数值
y = np.linspace(-1, 1, 100)  # 同理
X, Y = np.meshgrid(x, y)  # 根据输入的两个分别一维的函数向量创建相应的二维矩阵用于3D图像的表面绘制
Z = np.sin(np.sqrt(X**2 + Y**2))  # 根据X和Y数组生成Z数组

# 在3D坐标系中绘制3D曲面
ax.plot_surface(X, Y, Z, cmap=plt.cm.Blues)  #调用plot_surface()方法和传入自定义配色,生成曲面图效果。
ax.set_xlabel('X Label')  #设置x轴标签
ax.set_ylabel('Y Label')  #设置y轴标签
ax.set_zlabel('Z Label')  #设置z轴标签
plt.title('3D Plot Example')  #设置图表标题
plt.show()  #显示图表

This example demonstrates how to create a simple 3D coordinate system. The first code block defines a basic 3D axis object, and then linspace()defines the graphics data according to the parameters of the function. Use 'np.meshgrid()' to generate the corresponding grid, and use the sin() function to calculate the defined graphic Z value, and finally draw the three-dimensional surface and add axis labels to it.

Annotated Line Chart

import matplotlib.pyplot as plt  #导入Matplotlib模块

x = [1, 2, 3, 4, 5]  #定义x轴数据
y = [10, 8, 6, 4, 2]  #定义y轴数据

plt.plot(x, y)  #用plot()函数绘制折线图
plt.xlabel('X Label')  #设置x轴标签
plt.ylabel('Y Label')  #设置y轴标签
plt.title('Line Chart with Annotations')  #设置标题

# 打开交互模式并添加文本注释
plt.ion()   #打开交互模式
plt.annotate('Low point', xy=(4, 2), xytext=(3.5, 8),
             arrowprops=dict(facecolor='black', shrink=0.05)) 
# 在指定点(4, 2)处增加一条注释线,并给该行添加一个说明小箭头。
plt.annotate('Interesting Point', xy=(3, 6), xytext=(1.5, 9),
             arrowprops=dict(facecolor='red', shrink=0.05))
# 让注释点稍微偏离目标点坐标(3, 6),同时以红色为基调。

plt.show()  #展示图表结果

In this example, in addition to the basic functionality seen in the previous example, here is how to enhance a Matplotlib chart by adding annotations on the figure. The function `anotate() 用于往图表上添加箭头和注释文字(在此示例中,我们可在关键点进行注释)。 ion()` function turns on the interactive mode to allow real-time comparison of the bottom and the selection process of interesting points.

draw multiple subplots

import numpy as np
import matplotlib.pyplot as plt

# 生成一些示例数据
x = np.linspace(0, 10, 100)  #创建线性空间数组,并精准地定义起始点、结束点和数量。
y1 = np.sin(x)  #根据 x 数组生成 y1 数据
y2 = np.cos(x)  #根据 x 数组生成 y2 数据

# 创建网格并放置两个子图
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)  
# 调用subplots()方法,创建两行一列的子图网格。sharex=True表示共享横坐标。

# 在第一个子图中绘制sin函数
ax1.plot(x, y1, 'r-', linewidth=2)  #调用plot()函数,在第一个子图中绘制sin函数,使用以红色为基调的单匹配线条。
ax1.set_ylabel('Sin')  #设置y轴标签

# 在第二个子图中绘制cos函数
ax2.plot(x, y2, 'g-', linewidth=2)  #调用plot()函数,在第二个子图中绘制cos函数,用以绿色为基调的单匹配线条。
ax2.set_xlabel('Time (s)')  #设置x轴标签
ax2.set_ylabel('Cos')  #设置y轴标签

# 添加标题
plt.suptitle('Example of Multiple Subplots')  #用suptitle()函数为整个图表添加一个标题

plt.show()  #显示图表

subplots()With the functions and parameters defined above sharex = True , Matplotlib charts with multiple subplots can be created.
Then simply set the x and y axis labels in separate subplots, and add an overall title to build the command's own independent chart.

Export Matplotlib graphics

import numpy as np
import matplotlib.pyplot as plt

# 生成一些示例数据
x = np.linspace(0, 10, 100)  #使用numpy模块中的np.linspace()函数生成一系列等间隔样本点
y = np.sin(x)

# 创建新的图形并绘制sin函数
fig = plt.figure()  #创建一个新的图形
plt.plot(x, y, 'r-', linewidth=2)  #用plot()函数在该图形上绘制以红色为基调的折线状图表
plt.xlabel('Time (s)')  #设置x轴标签
plt.ylabel('Amplitude')  #设置y轴标签
plt.title('Example of a Matplotlib Figure')  #设置标题

# 将图表保存成PDF文件
plt.savefig('example.pdf')  #使用savefig()函数将该图形以pdf格式保存

plt.show()  #展示图表结果

In most cases, if you want to embed a Matplotlib chart into a GUI application, you don't need to export it to an external file. However, situations such as storing charts as image files or data visualizations on linked websites may require outputting graphics to ensure that the output works as expected. savefig() The function calls the chart instance directly, passing in the filename of the target format, in this case, the PDF file format.

These examples demonstrate Matplotlib's core API syntax and basic functional configuration items, enough to enable you to start building a perfectly rendered chart from scratch. Of course, Matplotlib offers more advanced features and options that require a careful understanding of the documentation, switching the keyword arguments you need for development tasks, and exploring further.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/130795077