Matplotlib 安装与配置

在开始使用 Matplotlib 绘制惊艳图表之前,首先需要正确安装并进行必要配置。 本章将详细介绍不同环境下的安装方式、验证安装、解决中文乱码、选择绘图后端等核心配置。

✅ 安装前提

Matplotlib 需要 Python 环境(版本 3.8 及以上)。推荐使用虚拟环境(如 venvconda)进行安装,避免包冲突。

📦 安装 Matplotlib

方法一:使用 pip 安装(推荐)

打开终端或命令提示符,执行以下命令:

pip install matplotlib

如需安装特定版本,例如 3.5.0:pip install matplotlib==3.5.0

方法二:使用 conda 安装(Anaconda 用户)

如果你使用 Anaconda 或 Miniconda,可以通过 conda 安装:

conda install matplotlib

conda 会自动处理依赖,并优先从 conda-forge 频道获取最新版。

方法三:从源码安装(高级用户)

从 GitHub 克隆仓库并本地构建:

git clone https://github.com/matplotlib/matplotlib.git
cd matplotlib
pip install -e .

通常用于开发或尝试未发布的新功能。

🔍 验证安装

安装完成后,在 Python 交互环境或脚本中执行:

import matplotlib
print(matplotlib.__version__)   # 输出安装的版本号,例如 3.7.1

如果没有报错且正常输出版本号,说明安装成功。

⚙️ 基础配置

Matplotlib 的配置主要通过 matplotlibrc 文件或运行时修改 rcParams 实现。

配置文件位置

执行以下代码可以查看当前使用的配置文件路径:

import matplotlib
print(matplotlib.matplotlib_fname())  # 显示当前生效的 matplotlibrc 文件路径

你也可以在当前工作目录创建自定义 matplotlibrc 文件,覆盖全局配置。

运行时修改配置

通过 plt.rcParams 字典临时修改配置,例如设置默认图片大小和分辨率:

import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (8, 6)   # 默认图形大小
plt.rcParams['figure.dpi'] = 100           # 默认分辨率

🇨🇳 解决中文乱码问题

Matplotlib 默认字体不支持中文,直接绘制会出现方框乱码。解决方案:指定支持中文的字体(如 SimHei, Microsoft YaHei, 或系统已有中文字体)。

方法一:临时设置(推荐用于脚本)
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']   # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False     # 用来正常显示负号
方法二:永久修改配置文件

找到 matplotlibrc 文件,取消以下两行的注释并修改:

font.family: sans-serif
font.sans-serif: SimHei, DejaVu Sans, ...   # 将 SimHei 放在首位
axes.unicode_minus: False
小技巧: 如果你不知道系统中有哪些中文字体,可以执行以下代码查看所有可用字体:
import matplotlib.font_manager as fm
fonts = [f.name for f in fm.fontManager.ttflist if 'hei' in f.name.lower() or 'yahei' in f.name.lower()]
print(fonts)

🖥️ 后端(Backend)配置

后端决定了 Matplotlib 图表的显示方式。常见后端:

  • Agg:用于生成 PNG 等图像文件,不显示窗口(适用于服务器)。
  • TkAgg:使用 Tkinter 显示窗口(跨平台)。
  • Qt5Agg:使用 Qt5 显示窗口(需要安装 PyQt5)。
  • inline:Jupyter Notebook 中内嵌显示。

查看当前后端:

import matplotlib
print(matplotlib.get_backend())

切换后端(必须在导入 pyplot 之前):

import matplotlib
matplotlib.use('Agg')   # 例如使用无头后端
import matplotlib.pyplot as plt

或者在 matplotlibrc 中设置:backend: TkAgg

🎨 样式配置

Matplotlib 内置多种美观样式,可通过 plt.style.use() 快速应用:

import matplotlib.pyplot as plt
plt.style.use('ggplot')          # 类似 R 的 ggplot2 风格
plt.style.use('seaborn-v0_8')    # seaborn 风格(旧版)
plt.style.use('dark_background') # 深色背景

查看所有可用样式:

print(plt.style.available)

❓ 常见问题

  • 安装时出现 SSL 错误:尝试使用国内镜像源,如 pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
  • 中文显示仍为方框:检查字体名称是否正确,或下载中文字体(如 SimHei.ttf)并手动安装到 matplotlib 字体目录。
  • No module named 'tkinter':TkAgg 后端需要 Tk 支持,Linux 下可安装 python3-tk 包。

至此,Matplotlib 的安装与基础配置已经完成。下一章我们将绘制第一个真正的图表,从简单的线图开始。