Matplotlib 教程

Matplotlib 教程(Python 数据可视化入门)

Matplotlib 是 Python 最流行的绘图库,功能强大,适合绘制各种静态、动态和交互式图表。本教程从零开始,带你快速上手。


一、安装 Matplotlib

pip install matplotlib

建议在虚拟环境中安装(如 venvconda


二、导入库(标准方式)

import matplotlib.pyplot as plt
import numpy as np

plt 是常用别名,numpy 常用于生成数据


三、基本绘图:折线图

# 数据
x = [1, 2, 3, 4, 5]
y = [1, 4, 2, 3, 5]

# 绘图
plt.plot(x, y)
plt.show()

四、常用设置(美化图表)

plt.plot(x, y, 
         color='red',      # 线条颜色
         linewidth=2,      # 线宽
         linestyle='--',   # 线型:实线 '-', 虚线 '--', 点线 ':', 点划线 '-.'
         marker='o',       # 数据点标记
         markersize=8,     # 标记大小
         label='数据曲线')  # 图例标签

plt.title('我的第一个图表')           # 标题
plt.xlabel('X 轴')                     # X轴标签
plt.ylabel('Y 轴')                     # Y轴标签
plt.grid(True)                         # 显示网格
plt.legend()                           # 显示图例
plt.show()

五、多种图表类型

1. 散点图(Scatter)

plt.scatter(x, y, color='blue', s=100, alpha=0.7)
plt.show()

2. 柱状图(Bar)

categories = ['A', 'B', 'C', 'D']
values = [3, 7, 2, 5]

plt.bar(categories, values, color='skyblue', edgecolor='black')
plt.show()

3. 水平柱状图

plt.barh(categories, values, color='lightgreen')
plt.show()

4. 直方图(Histogram)

data = np.random.randn(1000)
plt.hist(data, bins=30, color='purple', alpha=0.7)
plt.show()

5. 饼图(Pie)

labels = ['苹果', '香蕉', '橙子', '葡萄']
sizes = [30, 25, 20, 25]

plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.axis('equal')  # 使饼图为正圆
plt.show()

六、多图布局(子图 Subplots)

fig, axes = plt.subplots(2, 2, figsize=(10, 8))  # 2行2列

# 子图1
axes[0, 0].plot(x, y, 'r-o')
axes[0, 0].set_title('折线图')

# 子图2
axes[0, 1].scatter(x, y, color='green')
axes[0, 1].set_title('散点图')

# 子图3
axes[1, 0].bar(categories, values)
axes[1, 0].set_title('柱状图')

# 子图4
axes[1, 1].hist(np.random.randn(500), bins=20)
axes[1, 1].set_title('直方图')

plt.tight_layout()  # 自动调整间距
plt.show()

七、保存图片

plt.plot(x, y)
plt.savefig('my_plot.png', dpi=300, bbox_inches='tight')
# 支持格式:png, jpg, pdf, svg 等

八、使用 NumPy 生成数据(推荐)

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')
plt.legend()
plt.show()

九、样式美化(Seaborn 风格)

plt.style.use('seaborn')  # 或 'ggplot', 'bmh', 'fivethirtyeight'

plt.plot(x, np.sin(x))
plt.show()

查看所有样式:

print(plt.style.available)

十、完整示例:综合图表

import matplotlib.pyplot as plt
import numpy as np

plt.style.use('seaborn-v0_8')

# 数据
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建画布
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# 左图:折线 + 填充
ax1.plot(x, y1, 'b-', label='sin(x)', linewidth=2)
ax1.plot(x, y2, 'r--', label='cos(x)', linewidth=2)
ax1.fill_between(x, y1, alpha=0.2)
ax1.set_title('正弦与余弦')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.legend()
ax1.grid(True, alpha=0.3)

# 右图:散点
ax2.scatter(x[::5], y1[::5], c=y2[::5], cmap='viridis', s=60, edgecolors='k')
ax2.set_title('散点图(颜色表示 cos 值)')
ax2.set_xlabel('x')
ax2.set_ylabel('sin(x)')

plt.tight_layout()
plt.savefig('sine_cosine.png', dpi=200)
plt.show()

常用资源

资源链接
官方文档matplotlib.org
示例图库matplotlib.org/stable/gallery
中文教程Matplotlib中文网

小贴士

  • plt.figure(figsize=(width, height)) 控制画布大小
  • plt.xlim()/plt.ylim() 设置坐标轴范围
  • plt.text(x, y, '文字') 添加文字
  • plt.annotate() 添加带箭头的注释

现在轮到你了!
打开 Python,复制上面的代码运行试试吧!

需要我为你生成一个 交互式 Jupyter Notebook 版本特定类型图表模板 吗?告诉我你的需求!

文章已创建 2481

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部