数据处理与统计分析——10-Pandas可视化-Matplotlib的常用API

Matplotlib

Matplotlib 是 Python 中最常用的 2D 绘图库之一,提供了灵活的绘图功能,常用于生成静态、动态和交互式图表。该库提供了一种基于对象的绘图 API,可以让用户创建复杂的可视化效果。

1. Pyplot API(面向状态的接口)

matplotlib.pyplot 提供了一组类似于 MATLAB 的简单接口,适合进行快速绘图。常用的函数式 API,如 plt.plot()plt.scatter() 等,用于绘制各种常见的图表。

常用的 pyplot 函数

  • plt.plot(x, y):绘制折线图。

  • plt.scatter(x, y):绘制散点图。

  • plt.bar(x, height):绘制柱状图。

  • plt.hist(x):绘制直方图。

  • plt.pie(x):绘制饼图。

  • plt.title(label):设置图表标题。

  • plt.xlabel(label):设置 x 轴标签。

  • plt.ylabel(label):设置 y 轴标签。

  • plt.legend():添加图例。

  • plt.show():显示图表。

    python 复制代码
    import matplotlib.pyplot as plt
    
    # 简单的折线图示例
    x = [1, 2, 3, 4, 5]
    y = [1, 4, 9, 16, 25]
    
    plt.plot(x, y)
    plt.title('Simple Line Plot')
    plt.xlabel('X axis')
    plt.ylabel('Y axis')
    plt.show()

2. 面向对象的接口

Matplotlib 也支持面向对象的绘图方式。用户可以通过操作 FigureAxes 对象来创建和控制图表。Figure 是图的容器,Axes 是实际的数据绘制区域,表示图表的坐标系。

python 复制代码
# 面向对象的绘图
fig, ax = plt.subplots()

ax.plot(x, y)
ax.set_title('Object-Oriented Line Plot')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')

plt.show()

重要对象:

  • Figure 对象:整个图的容器。它包含多个 Axes对象,也可以包含其他如 Legend、Text等组件。

    • fig = plt.figure():创建 Figure 对象。
    • fig.add_axes():向 Figure 添加 Axes
    • fig.savefig():保存图像。
  • Axes 对象:表示一个绘图区域,通常是 x和 y坐标轴。一个 Figure中可以有多个 Axes。

    • ax.plot(x, y):在 Axes 上绘制图形。
    • ax.set_title():设置标题。
    • ax.set_xlabel() / ax.set_ylabel():设置 x / y 轴标签。
  • Axis 对象:表示单独的 x 轴或 y 轴,控制刻度和标签。

    • ax.xaxis.set_label_position():设置 x 轴标签的位置。
    • ax.yaxis.set_major_locator():设置 y 轴的刻度。
    python 复制代码
    # 多个子图的创建
    fig, axs = plt.subplots(2, 2, figsize=(10, 10))
    
    axs[0, 0].plot(x, y)
    axs[0, 0].set_title('Plot 1')
    
    axs[0, 1].scatter(x, y)
    axs[0, 1].set_title('Scatter 1')
    
    axs[1, 0].bar(x, y)
    axs[1, 0].set_title('Bar 1')
    
    axs[1, 1].hist(y, bins=5)
    axs[1, 1].set_title('Histogram 1')
    
    plt.tight_layout()
    plt.show()

3. 自定义图表

Matplotlib 提供了丰富的自定义选项,允许用户修改图形的细节,如颜色、线条样式、坐标轴等。

  • 线条样式和颜色 :通过 colorlinestylelinewidth 参数设置线条属性。
  • 标记 :通过 marker 设置数据点的标记样式。
  • 坐标轴范围plt.xlim()plt.ylim() 控制坐标轴的显示范围。
  • 图例plt.legend() 用于添加图例。
python 复制代码
plt.plot(x, y, color='green', linestyle='--', marker='o', label='line 1')
plt.xlim(0, 6)
plt.ylim(0, 30)
plt.legend()
plt.show()

4. Matplotlib 交互式绘图

Matplotlib 还支持与 Jupyter Notebook 和其他交互式环境的集成,支持交互式绘图。

  • plt.ion():开启交互模式。

  • plt.ioff():关闭交互模式。

  • %matplotlib inline:在 Jupyter 中使用时直接显示图像。

    python 复制代码
    %matplotlib inline
    plt.plot(x, y)

5. 扩展与高级功能

  • 3D 绘图 :通过 mpl_toolkits.mplot3d 模块支持 3D 图形。

  • 动画:可以创建动画,如动态更新数据的图形。

  • 嵌入式图形:Matplotlib 支持与 GUI 工具(如 Tkinter、PyQt)集成。

    python 复制代码
    from mpl_toolkits.mplot3d import Axes3D
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    # 示例数据
    ax.scatter([1, 2, 3], [1, 2, 3], [1, 2, 3])
    plt.show()

6. 保存图像

使用 savefig() 方法可以将图表保存为各种格式,如 PNG、PDF 等。

python 复制代码
plt.savefig('plot.png', dpi=300, format='png')
相关推荐
失败尽常态52336 分钟前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_9044477438 分钟前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农38 分钟前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿44 分钟前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
夏末秋也凉1 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
Leuanghing1 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
王老师青少年编程1 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
xinxiyinhe2 小时前
如何设置Cursor中.cursorrules文件
人工智能·python
诸神缄默不语3 小时前
如何用Python 3自动打开exe程序
python·os·subprocess·python 3
橘子师兄3 小时前
分页功能组件开发
数据库·python·django