Python data visualization development (1): Basic knowledge of Matplotlib library


foreword

insert image description here

  • Matplotlib is a plotting library for Python that allows users to easily visualize data and provide a variety of output formats.
  • Matplotlib can be used to draw various static, dynamic, and interactive charts.
  • Matplotlib is a very powerful Python drawing tool, we can use this tool to present a lot of data more intuitively in the form of charts.
  • Matplotlib can draw line plots, scatterplots, contour plots, bar charts, histograms, 3D graphics, even graphic animations, and more.

使用Matplotlib生成一个曲线的完整代码(其中部分代码是可以省略的,为了便于将相关属性快速有效的予以记录,本文尽量将相关属性都列了出来。)

# 导入库
import numpy as np
import matplotlib.pyplot as plt

# 设置中文显示
plt.rcParams['font.sans-serif'] = ['microsoft yahei']  #显示中文

# 01.工具栏组件
plt.rcParams['toolbar'] = 'toolbar2'  # 设置工具栏

# 02.模拟数据
x = np.linspace(0.0, 5.0, 100)
y = np.cos(2 * np.pi * x) * np.exp(-x)

# 03.设置字体字典
font = {
    
    'family': 'microsoft yahei',
        'color': '#000',
        'weight': 'normal',
        'size': 12}

# 04.图像配置实例
plt.figure('漏刻有时数据可视化 - TestWin', facecolor='w')  # 设置图形弹出窗口标题
# 05.图表标题
plt.title('漏刻有时折线图', fontdict=font, loc='center', y=1)  # 图表标题
# 06.文本组件
plt.text(0.91, -0.31, r'智能化数据的转账点', fontdict=font, c='b', rotation=30)  # 文本
# 07.坐标轴标签组件
plt.xlabel('时间:单位 (s)', fontdict=font)  # x轴
plt.ylabel('数值:单位 (mv)', fontdict=font)  # y轴
# 08.网格组件
plt.grid(which='major', axis='both', color='g', linestyle='-', linewidth=0.1)  # 网格
# 09.绘制折线
plt.plot(x, y, 'r', label='直连线', marker='d')  # 绘制折线
# 10.图例组件
plt.legend()  # 设置图例
# 11.图表渲染
plt.show()

01. Toolbar components

'''
工具栏组件
# 注意,应当放置在图像实例化之前。
# None模式:禁用工具栏
# toolbar2模式:默认工具栏布局
# toolmanager模式:工具栏布局在首行
'''
plt.rcParams['toolbar'] = 'toolbar2'  # 设置工具栏

toolmanager mode:
insert image description here
RcParams documentation: RcParams

02. Chart data

Line charts are generally x-axis and y-axis data, which can be set to the corresponding list. As the basic knowledge of the Matplotlib library, this case only does simple data display and does not involve more complex data reading and calculation.
like:

  • numpy mock data
x = np.linspace(0.0, 5.0, 100)
y = np.cos(2 * np.pi * x) * np.exp(-x)
  • custom fixed data
x = [1, 2, 3, 4, 5]
y = [i * 2 for i in x] #推导式
  • random random data
x = [random.randint(0, 10) for i in range(10)]
y = [i * 2for i in x]
  • Pandas reads local excel table data
  • pymysql read database data

03. Set font dictionary

global font style

If Matplotlib does not set the Chinese font normally, garbled characters will appear. Based on the actual development situation, image titles, chart titles, legends and labels all involve the application of Chinese fonts, so the rcParams using the matplotlib module, the global font style:

plt.rcParams['font.sans-serif'] = ['microsoft yahei']`

Of course, you can also call the corresponding properties separately when some components are used, such as:

plt.title('自定义标题名称', fontproperties='SimHei')

Corresponding names of commonly used Chinese fonts

Chinese name English name
Times New Roman SimSun
black body SimHey
Microsoft Yahei Microsoft YaHei
Microsoft Positive Heibody Microsoft Jheng Hei
Neo-Arial NSimSun
new details PMingLiU
fine body Ming LiU
Regular font DFKai-SB
Imitation of Song Dynasty Fang Song
italics Eat Tea
official script LiSu
Yodo YouYuan
Chinese italics STChange
Chinese Song Typeface STSong
Chinese Song STZhongsong
Chinese imitation of Song Dynasty STFangsong

Query all fonts in the current system

If you want to query all the fonts of the current system in real time, you can use the attributes that come with matploylib font_managerto perform traversal queries:

# 查询当前系统所有字体
from matplotlib.font_manager import FontManager
sys_fonts = [f.name for f in FontManager().ttflist]
for f in sorted(sys_fonts):
    print(f)

Display of font results:
insert image description here

04. Example of image configuration

configuration format

The plt.figure() function can be used to create a drawing window, and the following common parameters can be passed in:

matplotlib.figure.Figure(figsize=None, dpi=None, *, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None, layout=None, **kwargs)
如:

# 配置实例
plt.figure('漏刻有时数据可视化 - TestWin', facecolor='w')  # 设置图形弹出窗口标题

insert image description here

Parameter Description

parameter illustrate
num Pass in an integer or string. The integer can specify to create or activate the corresponding numbered window and save it to the number property, and the string can set the title of the window
figsize Pass in a tuple of two floating-point numbers to set the width and height of the drawing window
dpi Pass in an integer to set the resolution
facecolor Pass in a string representing the color to set the background color
edgecolor Pass in a string representing the color to set the border color
clear If True is passed in, and the current window already has a drawing, clear the current drawing

Official documentation: matplotlib.figure

05. Chart title

configuration format

matplotlib.pyplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)

Parameter Description

parameter illustrate options
label text content string
fontdict font format ‘fontweight’: rcParams[‘axes.titleweight’], ‘color’: rcParams[‘axes.titlecolor’]
loc Location 'center', 'left', 'right', default: 'center'
y Y axis position 1.0 is the top
**quargs text attribute

Official documentation:

matplotlib.pyplot.title

06. Text component

configuration format

matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)

Parameter Description

parameter illustrate
x,y where to place the text, by default, in data coordinates
s text content;
fontdict A dictionary to override the default text attributes, if None the defaults are determined by rcParams
**quargs Common configuration options: color, fontfamily, fontsize, fontweight, rotation, transform, etc.

Official documentation:

matplotlib.pyplot.text

07. Axis Label Component

configuration format

The configuration format and parameters of xlabel and ylabel are the same.

matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)

parameter configuration

parameter illustrate
ylabe String, y-axis specification
labelpad The point spacing from the axes bounding box (including ticks and tick labels). If "none", the previous value remains as it is
loc 'bottom', 'center', 'top', default 'center'
**quargs The text attribute controls the appearance of the label, you can refer to the Text attribute

Official documentation:

matplotlib.pyplot.ylabel

08. Grid Components

configuration format

matplotlib.pyplot.grid(visible=None, which=‘major’, axis=‘both’, **kwargs)

参数配置

参数 说明
visible 是否显示网格线,选项:bool or None
which 要更改的网格线
axis {‘both’, ‘x’, ‘y’}
**kwargs 文本属性控制标签的外观,可以参考Text属性

官方文档:

matplotlib.pyplot.grid

09.绘制折线

配置格式

matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)

参数配置

plot([x], y, [fmt], *, data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
参数 说明
x 传入序列、列表类型的对象,包含各个点的横坐标数值,默认为 0~len(y)-1
y 传入序列、列表类型的对象,包含各个点的纵坐标数值
fmt 传入一个字符串,代表所绘制线条的样式(按颜色、点型、线型顺序)1
data 关键字参数,传入一个具有索引功能的对象,此时 x、y 只需传入一个字符串来表示是该对象的这个索引

kwargs 中常用参数:

参数 说明
color 设置线条的颜色,可用十六进制的RGB字符串精确设置颜色
label 设置线条的标签

fmt 参数用法

fmt 参数传入一个字符串,按颜色、点型、线型的顺序拼接而成。

颜色(可用 color 参数代替):

字符串 含义
‘b’ blue 蓝色
‘g’ green 绿
‘r’ red 红
‘c’ cyan 蓝绿
‘m’ magenta 洋红
‘y’ yellow 黄
‘k’ black 黑
‘w’ white 白

点型(可用 marker 参数代替)

字符串 含义
‘.’ point marker
‘,’ pixel marker
‘o’ circle marker
‘v’ triangle_down marker
‘^’ triangle_up marker
‘<’ triangle_left marker
‘>’ triangle_right marker
‘1’ tri_down marker
‘2’ tri_up marker
‘3’ tri_left marker
‘4’ tri_right marker
‘s’ square marker
‘p’ pentagon marker
‘*’ star marker
‘h’ hexagon1 marker
‘H’ hexagon2 marker
‘+’ plus fields
‘x’ x marker
‘D’ diamond marker
‘d’ thin_diamond marker
vertical line vline marker
‘_’ clay marker

Line style (can be replaced by linestyle parameter):

string meaning
‘-’ solid line style solid line
‘–’ dashed line style dashed line
‘-.’ dash-dot line style dotted line
‘:’ dotted line style point

Official documentation:

matplotlib.pyplot.plot

10. Legend component

configuration format

matplotlib.pyplot.legend(*args, **kwargs)

parameter configuration

legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)

Official documentation:

matplotlib.pyplot.legend

11. Chart rendering

Show all graphics.

matplotlib.pyplot.show(*, block=None)


Summarize

The basic option attributes of Matplotlib are subject to the official website https://matplotlib.org/stable/api/pyplot_summary.html , because it is in English, in the actual learning and development process, you need to practice as much as possible.

Guess you like

Origin blog.csdn.net/weixin_41290949/article/details/128761262