数据处理与统计分析——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')
相关推荐
孟健9 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞11 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽14 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程18 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪18 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
Duang19 小时前
从零推导指数估值模型 —— 一个三因子打分系统的设计思路
数据分析·领域驱动设计
databook19 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img