问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Matplotlib完全指南:数据可视化从入门到实战

创作时间:
作者:
@小白创作中心

Matplotlib完全指南:数据可视化从入门到实战

引用
CSDN
1.
https://blog.csdn.net/qq_67342067/article/details/146375242

Matplotlib是Python最强大的数据可视化库,可以创建高质量的2D/3D图形,完美支持科学计算与数据分析。本文将深入讲解Matplotlib的核心功能,通过20+个实战案例,带你从基础绘图到高级可视化技巧,全面掌握数据图形化表达!

一、环境配置与基础概念

1.1 安装Matplotlib

pip install matplotlib

1.2 导入惯例

import matplotlib.pyplot as plt  # 主要接口
import numpy as np               # 配合使用

1.3 两种绘图模式

  • 脚本模式
plt.plot() + plt.show()
  • 面向对象模式(推荐):
fig, ax = plt.subplots()
ax.plot(x, y)

二、基础图形绘制

2.1 折线图(Line Plot)

x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(8,4))
ax.plot(x, y, 
        color='red', 
        linestyle='--', 
        linewidth=2,
        marker='o',
        markersize=5,
        label='sin(x)')
ax.set_title("正弦曲线示例")
ax.set_xlabel("X轴")
ax.set_ylabel("Y轴")
ax.legend()
plt.show()

2.2 柱状图(Bar Chart)

categories = ['A', 'B', 'C', 'D']
values = [25, 40, 30, 45]
fig, ax = plt.subplots()
bars = ax.bar(categories, values, 
             color=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'],
             edgecolor='black')
# 添加数值标签
for bar in bars:
    height = bar.get_height()
    ax.text(bar.get_x() + bar.get_width()/2., height,
            f'{height}',
            ha='center', va='bottom')
ax.set_ylim(0, 50)
ax.grid(axis='y', linestyle='--')

三、高级图表类型

3.1 散点图(Scatter Plot)

x = np.random.randn(100)
y = x * 2 + np.random.randn(100)
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, 
                    c=np.abs(x+y),  # 颜色映射
                    s=50,          # 点大小
                    cmap='viridis',
                    alpha=0.7)
plt.colorbar(scatter, label='强度值')

3.2 饼图(Pie Chart)

labels = ['电子产品', '服饰', '食品', '图书']
sizes = [35, 25, 20, 20]
explode = (0.1, 0, 0, 0)  # 突出显示第一项
fig, ax = plt.subplots()
ax.pie(sizes, 
       explode=explode,
       labels=labels,
       autopct='%1.1f%%',
       shadow=True,
       startangle=90)
ax.axis('equal')  # 正圆形

3.3 直方图(Histogram)

data = np.random.normal(170, 10, 1000)
fig, ax = plt.subplots()
ax.hist(data, bins=30,
        density=True,   # 显示概率密度
        histtype='stepfilled',
        color='skyblue',
        edgecolor='black')
ax.set_xlabel("Height distribution")
ax.set_ylabel("probability density")

四、多图布局与样式定制

4.1 子图布局(Subplots)

x = np.random.randn(100)
y = x * 2 + np.random.randn(100)
data = np.random.normal(170, 10, 1000)
labels = ['electronics', 'costume', 'food', 'book']
sizes = [35, 25, 20, 20]
fig, axs = plt.subplots(2, 2, figsize=(10,8))
# 第一个子图
axs[0,0].plot(x, y)
axs[0,0].set_title("折线图")
# 第二个子图
axs[0,1].scatter(x, y)
# 第三个子图
axs[1,0].hist(data)
# 第四个子图
axs[1,1].pie(sizes, labels=labels)
plt.tight_layout()  # 自动调整间距

4.2 样式定制(StyleCustomization)

x = np.random.randn(10)
y = x * 2 + np.random.randn(10)
plt.style.use('ggplot')  # 使用内置主题
fig, ax = plt.subplots()
ax.plot(x, y, 
        linewidth=2,
        marker='D',
        markersize=8,
        markerfacecolor='yellow',
        markeredgecolor='black')
# 设置刻度参数
ax.tick_params(axis='both', 
              which='major', 
              labelsize=12,
              direction='inout')
# 设置网格线
ax.grid(True, 
       linestyle='--', 
       alpha=0.6)
# 设置坐标轴范围
ax.set_xlim(0, 10)
ax.set_ylim(-1.5, 1.5)

五、三维可视化

5.1 3D曲面图

from mpl_toolkits.mplot3d import Axes3D
X = np.linspace(-5, 5, 100)
Y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(X, Y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(X, Y, Z, 
                      cmap='viridis',
                      antialiased=True)
fig.colorbar(surf, shrink=0.5)

六、实战案例:销售数据分析

案例1:多维度销售趋势分析

months = ['Jan', 'Feb', 'Mar', 'Apr']
sales_2023 = [120, 145, 178, 205]
sales_2024 = [135, 160, 190, None]  # 模拟缺失值
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12,5))
# 左侧:双折线图
ax1.plot(months, sales_2023, marker='o', label='2023')
ax1.plot(months[:3], sales_2024[:3], marker='s', label='2024')
ax1.set_title("月度销售趋势对比")
ax1.legend()
# 右侧:柱状图
ax2.bar(months, sales_2023, alpha=0.7, label='2023')
ax2.bar(months, sales_2024, alpha=0.7, label='2024', 
        bottom=sales_2023)
ax2.set_title("累计销售额对比")

案例2:动态交互式可视化

from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = ax.plot([], [], 'ro')
def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,
def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

七、高级技巧与优化

7.1 样式美化

plt.rcParams.update({
    'font.family': 'SimHei',        # 中文字体
    'font.size': 12,
    'axes.titlesize': 14,
    'axes.labelsize': 12
})

7.2 输出高清图像

fig.savefig('output.png', 
           dpi=300,          # 分辨率
           bbox_inches='tight', 
           facecolor='white')

7.3 性能优化

  • 使用 ax.plot() 替代多次 plt.plot()
  • 对于大数据集使用 numpy 进行预计算
  • 关闭交互模式:plt.ioff()

八、常见问题解决方案

8.1 中文显示问题

# 方法1:指定中文字体
plt.rcParams['font.family'] = 'SimHei'
# 方法2:动态加载字体
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='msyh.ttc', size=12)
ax.set_title("标题", fontproperties=font)

8.2 坐标轴科学计数法

ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0))

结语

Matplotlib是数据可视化的瑞士军刀,本文涵盖了其核心功能的80%。建议通过以下方式精进:

  1. 每天练习一种图表类型
  2. 研究优秀可视化案例的源码
  3. 学习结合Pandas直接绘图
  4. 探索Seaborn等高级封装库
© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号