千家信息网

matplotlib库有什么用

发表于:2024-10-09 作者:千家信息网编辑
千家信息网最后更新 2024年10月09日,这篇文章主要介绍matplotlib库有什么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!Matplotlib 是一个 Python 的 2D绘图库(当然也可以画三维形式的图
千家信息网最后更新 2024年10月09日matplotlib库有什么用

这篇文章主要介绍matplotlib库有什么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

Matplotlib 是一个 Python 的 2D绘图库(当然也可以画三维形式的图形哦),它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形 。通过 Matplotlib,开发者仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等。

Matplotlib 主要有两大模块:pyplot 和 pylab,这二者之间有何区别和联系呢?

首先 pyplot 和 pylab 都可以画出图形,且两者 API 也是类似的, 其中 pylab 包括了许多 numpy 和 pyplot 模块中常用的函数,对交互式使用(如在 IPython 交互式环境中)来说比较方便,既可以画图又可以进行计算,不过官方推荐对于项目编程最好还是分别导入 pyplot 和 numpy 来作图和计算。

先来个简单的

import numpy as npfrom matplotlib import pyplot as pltx = np.arange(0, 11)y = 2*xplt.plot(x, y, marker='o')plt.show()

同一幅图中多条线

x = np.arange(0, 11)y1 = 2*xy2 = 4*x# g-- 表示绿色虚线  r- 表示红色实线plt.plot(x, y1, 'g--') plt.plot(x, y2, 'r-')plt.show()

Matplotlib Api 风格

Matplotlib 有两种编程风格,一种是 Matlab 用户熟悉的风格,一种是面向对象式的风格,推荐后者

Matlab 风格的 Api

plt.figure(figsize=(10, 5))x = [1, 2, 3]y = [2, 4, 6]plt.plot(x, y, 'r')plt.xlabel('x axis')plt.ylabel('y axis')plt.title('figure title')plt.show()

面向对象风格的 Api

fig = plt.figure(figsize=(10, 5))# add_subplot(nrows, ncols, index, **kwargs) 默认 (1, 1, 1)axes = fig.add_subplot()x = [1, 2, 3]y = [2, 4, 6]axes.plot(x, y, 'r')axes.set_xlabel('x axis')axes.set_ylabel('y axis')axes.set_title('figure title')plt.show()

都得到以下图形

多个子图

fig: plt.Figure = plt.figure(figsize=(10, 5))axes1 = fig.add_subplot(2, 1, 1)  # (nrows, ncols, index)# 与 axes1 共享x,y轴# the axis will have the same limits, ticks, and scale as the axis# facecolor: 坐标轴图形背景颜色axes2 = fig.add_subplot(2, 1, 2, sharex=axes1, sharey=axes1, facecolor='k')x = np.linspace(-5, 5, 100)y1 = np.sin(x)y2 = np.cos(x)axes1.plot(x, y1, color='red', linestyle='solid')axes2.plot(x, y2, color='#00ff00', linestyle='dashed')axes1.set_title('axes1 title')axes2.set_title('axes2 title')plt.show()

# 设置图的位置、大小axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])  # [left, bottom, width, height]axes2 = fig.add_axes([0.7, 0.7, 0.2, 0.2])

对象关系

在 matplotlib 中,整个图像为一个 Figure 对象。在 Figure 对象中可以包含一个,或者多个 Axes 对象,每个 Axes 对象都是一个拥有自己坐标系统的绘图区域。

Title--标题Axis--坐标轴Label--坐标轴标注Tick--刻度线Tick Label--刻度注释

简写形式

点标记

只列出了常用的(只支持简写形式)

图例

axes.plot(x, y, 'r', label='y=2x')# oraxes.set_label('y=2x')axes.legend(loc='upper right')  # 默认 legend(loc='best')# 同时设置多个plt.legend((axes1, axes2, axes3), ('label1', 'label2', 'label3'))

调整坐标轴的上下限

# xlim(left=None, right=None, emit=True, auto=False, *, xmin=None, xmax=None) # ylim(bottom=None, top=None, emit=True, auto=False, *, ymin=None, ymax=None) axes.set_xlim(0, 8)axes.set_ylim(0, 8)

直至坐标轴显示间隔

from matplotlib.ticker import MultipleLocator# 如设置主要刻度线间隔为 2axes.xaxis.set_major_locator(MultipleLocator(2))

调整坐标轴标签的显示

# 当点比较密集时,x 轴刻度线标签可能会重叠在一起,尤其是时间时# 1. 对于时间可以使用 autofmt_xdate 自动调整对齐和旋转fig.autofmt_xdate()# 2. 通用的ax.set_xticklabels(xticks, rotation=30, ha='right')# 对于日期显示还可以自定义格式from matplotlib.dates import DateFormatterax.xaxis.set_major_formatter(DateFormatter('%Y-%m'))

设置坐标轴名称

# 坐标轴下方或左边显示的标签ax.set_xlabel('Time Series')ax.set_ylabel('Microseismicity')

综合示例

fig = plt.figure()axes = fig.add_subplot()t = np.linspace(0, np.pi, 64)x = np.sin(t)y = np.cos(t) + np.power(x, 2.0 / 3)# 采用参数定义样式axes.plot(x, y, color='red', marker='o', linestyle='solid', linewidth=2, label='x>0')# 采用简写 color marker linestyle 没有顺序之分,不需要都写axes.plot(-x, y, 'ro-', linewidth=2, label='x<0')# 设置标题axes.set_title('心型图', fontdict={'size': 16, 'color': 'r', 'family': 'SimHei'})# 设置坐标轴数值范围axes.set_xlim(-1.5, 1.5)# 设置坐标轴刻度线axes.set_xticks([-1.5, -1, 0, 1, 1.5])# 设置坐标轴刻度线标签,不设置则是坐标轴数值axes.set_xticklabels(['-1.5', '-1', '原点', '1', '1.5'], fontdict={'family': 'SimHei'})# 设置显示图例axes.legend()# 设置显示网格线axes.grid(color='#cccccc', ls='-.', lw=0.25)plt.show()

一些配置项

# 使用 pycharm 运行 plt.show() 默认不在独立窗口显示(terminal 运行可以)# 切换 backend 为 TkAgg 时, pycharm 运行可以在独立窗口展示图,同时 terminal 运行也可以# 默认 non-interactive backends = agg# 如果不切换 backend 又想在独立窗口显示,可以按如下设置# File -> Settings -> Tools -> Python Scientific -> 去掉Show plots in tool window勾选plt.switch_backend('TkAgg')# 当 figure 开启超过 20 个时会有警告(一般循环画图出现),可以主动 close 图for y in data:    fig: plt.Figure = plt.figure()    axes = fig.add_subplot()    axes.plot(y, color='red', marker='o', linestyle='solid')    plt.savefig('xxx.png')    plt.close()# 设置网格线plt.grid(True)# 设置字体,默认不支持中文显示,可以指定中文字体来显示中文plt.rcParams["font.family"] = 'SimHei'  # mac os可以使用 Heiti TC# 也可以在使用的时候分别设置axes.set_title('中文字体 SimHei', fontdict={'size': 16, 'color': 'r', 'family': 'SimHei'})# 解决坐标轴负数的负号显示问题plt.rcParams['axes.unicode_minus'] = False

图形类型

以上是"matplotlib库有什么用"这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!

0