程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

Python Matplotlib 入门教程:可视化数据的基石

balukai 2025-05-03 12:14:15 文章精选 1 ℃

一、简介

Matplotlib 是 Python 中最流行的数据可视化库,提供从简单折线图到复杂3D图形的完整解决方案。其核心优势在于:
o 灵活性强:支持像素级样式控制
o 兼容性好:与 NumPy、Pandas 无缝协作
o 扩展性强:支持 LaTeX 公式、动画等高级功能

二、安装与导入

pip install matplotlib

导入方式与Jupyter设置:

import matplotlib.pyplot as plt  # 标准导入方式
import numpy as np               # 用于生成示例数据
%matplotlib inline                # 在Jupyter中内嵌显示图表

三、核心概念:Figure与Axes

# Figure相当于画布,Axes是绘图区域
fig = plt.figure(figsize=(8, 6))  # 创建8x6英寸的画布
ax = fig.add_subplot(1,1,1)       # 添加一个1x1的绘图区域
ax.plot([1,2,3], [4,5,1])        # 在Axes上绘图
plt.show()

四、两种绘图模式对比

1. pyplot快捷模式(适合简单图表)

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label='sin(x)')
plt.title('Quick Plot Demo')
plt.legend()
plt.show()

2. 面向对象模式(适合复杂图表)

fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(x, np.cos(x), color='red', linestyle='--', label='cos(x)')
ax.set_title('OOP Style Demo')
ax.legend()
plt.show()

五、常见图表类型

1. 折线图(趋势分析)

# 对比两条产品线季度销售额
quarters = ['Q1', 'Q2', 'Q3', 'Q4']
product_A = [230, 450, 300, 700]
product_B = [180, 400, 350, 650]

fig, ax = plt.subplots()
ax.plot(quarters, product_A, marker='o', label='Product A')
ax.plot(quarters, product_B, marker='s', label='Product B')
ax.set_title('Quarterly Sales Trend')
ax.set_xlabel('Quarter')
ax.set_ylabel('Sales (Million $)')
ax.grid(alpha=0.3)
ax.legend()
plt.show()

2. 柱状图(类别对比)

# 不同编程语言使用率对比
languages = ['Python', 'Java', 'C++', 'JavaScript']
popularity = [75, 60, 45, 55]

fig, ax = plt.subplots()
bars = ax.bar(languages, popularity, color=['#2ca02c', '#d62728', '#1f77b4', '#9467bd'])
ax.set_title('Programming Language Popularity')
ax.set_ylabel('Usage (%)')

# 为每个柱子添加数值标签
for bar in bars:
    height = bar.get_height()
    ax.text(bar.get_x() + bar.get_width()/2, height,
            f'{height}%',
            ha='center', va='bottom')
plt.show()

3. 散点图(相关性分析)

# 汽车价格与马力的关系
np.random.seed(42)
price = np.random.normal(35000, 15000, 100)
horsepower = 0.8 * price + np.random.normal(0, 5000, 100)

fig, ax = plt.subplots()
scatter = ax.scatter(price, horsepower, c=horsepower, cmap='viridis', alpha=0.7)
ax.set_title('Car Price vs Horsepower')
ax.set_xlabel('Price ($)')
ax.set_ylabel('Horsepower')
fig.colorbar(scatter, label='Horsepower')  # 添加颜色条
plt.show()

4. 直方图(分布分析)

# 学生考试成绩分布
scores = np.random.normal(75, 10, 200)

fig, ax = plt.subplots()
ax.hist(scores, bins=20, edgecolor='black', alpha=0.7)
ax.set_title('Exam Score Distribution')
ax.set_xlabel('Score')
ax.set_ylabel('Frequency')
ax.axvline(scores.mean(), color='red', linestyle='--', label='Mean')  # 添加均值线
ax.legend()
plt.show()

六、高级样式控制

1. 全局样式设置

plt.style.use('ggplot')  # 应用杂志风格
print(plt.style.available)  # 查看所有内置样式

2. 坐标轴高级设置

fig, ax = plt.subplots()
ax.plot(x, np.tan(x))

# 设置坐标轴范围与刻度
ax.set_xlim(0, 10)
ax.set_ylim(-5, 5)
ax.set_xticks(np.arange(0, 11, 2))  # 每2个单位一个刻度
ax.set_xticklabels(['Start', '2', '4', '6', '8', 'End'])  # 自定义标签

# 添加参考线
ax.axhline(0, color='black', linewidth=0.8)  # x轴参考线

3. 双坐标轴示例

# 温度与降水量双轴图表
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
temp = [5, 7, 11, 16, 21]
rainfall = [80, 60, 45, 30, 20]

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

ax1.plot(months, temp, 'r-', marker='o', label='Temperature')
ax2.bar(months, rainfall, alpha=0.3, label='Rainfall')

ax1.set_ylabel('Temperature (°C)', color='red')
ax2.set_ylabel('Rainfall (mm)', color='blue')
fig.legend(loc='upper left')
plt.show()

七、子图与布局

1. 网格布局

fig, axs = plt.subplots(2, 2, figsize=(10, 8))

# 左上:折线图
axs[0,0].plot(x, np.sin(x), color='blue')
axs[0,0].set_title('Sine Wave')

# 右上:柱状图
axs[0,1].bar(['A', 'B', 'C'], [25, 40, 30], color='orange')

# 左下:散点图
axs[1,0].scatter(np.random.rand(50), np.random.rand(50), c='green')

# 右下:饼图
axs[1,1].pie([30, 70], labels=['Yes', 'No'], autopct='%1.1f%%')

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

2. 自定义复杂布局

fig = plt.figure(figsize=(12, 6))
gs = fig.add_gridspec(2, 2)  # 创建2x2网格

ax_main = fig.add_subplot(gs[:, 0])     # 左列合并
ax_right = fig.add_subplot(gs[0, 1])    # 右上
ax_bottom = fig.add_subplot(gs[1, 1])   # 右下

ax_main.plot(x, np.sin(x))
ax_right.pie([20, 80], labels=['A', 'B'])
ax_bottom.scatter(x, np.cos(x))
plt.show()

八、实战技巧

1. 解决中文显示问题

plt.rcParams['font.sans-serif'] = ['SimHei']  # Windows系统
plt.rcParams['axes.unicode_minus'] = False    # 解决负号显示异常

2. 结合Pandas使用

import pandas as pd
df = pd.read_csv('sales_data.csv')

fig, ax = plt.subplots()
ax.plot(df['date'], df['revenue'], label='营收')
ax.plot(df['date'], df['cost'], label='成本')
ax.set_title('公司月度财务趋势')
ax.legend()
plt.show()

3. 保存高质量图片

plt.savefig('analysis_report.png',
            dpi=300,               # 高分辨率
            bbox_inches='tight',   # 去除白边
            transparent=True,      # 透明背景
            facecolor='white'      # 画布颜色
           )

九、学习建议

  1. 官方资源
  • 文档:matplotlib.org
  • 示例库:plt.gallery() 查看所有示例
  1. 调试技巧
print(ax.get_children()) # 查看所有图表元素
  1. 进阶路线
  • 学习Seaborn库简化统计图表
  • 探索mplot3d绘制3D图形
  • 使用Plotly制作交互式图表
最近发表
标签列表