Matplotlib 数据可视化 - 基础入门

Matplotlib 图表绑制基础教程,包含折线图、柱状图、散点图等

预计阅读时间:3 分钟

Matplotlib 数据可视化 - 基础入门

Matplotlib 是 Python 最流行的数据可视化库!


目录

  1. 什么是 Matplotlib?
  2. 基本绘图
  3. 常用图表
  4. 图表美化
  5. 与 Seaborn 结合

1. 什么是 Matplotlib?

Matplotlib 用于创建各种静态、动态、交互式图表。

常用图表类型: - 折线图 - 柱状图 - 散点图 - 直方图 - 饼图


2. 基本绘图

import matplotlib.pyplot as plt
import numpy as np

# 简单折线图
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2)
plt.xlabel('X 轴')
plt.ylabel('Y 轴')
plt.title('正弦波')
plt.grid(True)
plt.show()

3. 常用图表

柱状图

categories = ['A', 'B', 'C', 'D']
values = [25, 40, 30, 55]

plt.figure(figsize=(8, 5))
plt.bar(categories, values, color=['#3498db', '#e74c3c', '#2ecc71', '#f39c12'])
plt.title('销售数据')
plt.xlabel('产品')
plt.ylabel('销量')
plt.show()

散点图

x = np.random.rand(50)
y = np.random.rand(50)

plt.figure(figsize=(8, 5))
plt.scatter(x, y, c='blue', alpha=0.6, s=100)
plt.title('随机散点')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

4. 图表美化

# 设置样式
plt.style.use('seaborn-v0_8-darkgrid')

# 中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 创建子图
fig, axes = plt.subplots(2, 2, figsize=(12, 10))

axes[0, 0].plot(x, y)
axes[0, 1].bar(categories, values)
axes[1, 0].hist(np.random.randn(100), bins=20)
axes[1, 1].scatter(x, y)

plt.tight_layout()
plt.show()

5. 与 Seaborn 结合

import seaborn as sns

# Seaborn 内置主题
sns.set_theme(style="darkgrid")

# 使用内置数据集
tips = sns.load_dataset("tips")

# 绑制
sns.relplot(data=tips, x="total_bill", y="tip", hue="smoker", kind="scatter")
plt.show()

常用配色方案

风格 说明
seaborn-darkgrid 默认风格
ggplot R 语言风格
bmh 简约风格

标签: #Python #Matplotlib #数据可视化


本文由 suisui 发布