← 返回首页
🤖

Matplotlib数据可视化

📂 ai ⏱ 2 min 334 words

Matplotlib数据可视化

Matplotlib是Python最基础的绑图库,也是Seaborn、Plotly等高级可视化库的基础。掌握Matplotlib将帮助你创建各种专业的数据可视化图表。

基础折线图

折线图是最常用的图表类型,适合展示数据随时间的变化趋势。

import matplotlib.pyplot as plt
import numpy as np

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

months = ['1月', '2月', '3月', '4月', '5月', '6月']
sales = [100, 120, 110, 150, 140, 180]
profit = [20, 25, 22, 35, 30, 45]

plt.figure(figsize=(10, 6))
plt.plot(months, sales, marker='o', linewidth=2, label='销售额')
plt.plot(months, profit, marker='s', linewidth=2, linestyle='--', label='利润')

plt.title('月度销售趋势', fontsize=16)
plt.xlabel('月份', fontsize=12)
plt.ylabel('金额(万元)', fontsize=12)
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('line_chart.png', dpi=150)
plt.show()

柱状图

柱状图适合比较不同类别的数值大小。

categories = ['技术', '市场', '销售', '运营', '人事']
values = [85, 72, 90, 65, 55]
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']

plt.figure(figsize=(10, 6))
bars = plt.bar(categories, values, color=colors, edgecolor='black', linewidth=0.5)

for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height,
             f'{height}', ha='center', va='bottom', fontsize=10)

plt.title('各部门绩效评分', fontsize=16)
plt.xlabel('部门', fontsize=12)
plt.ylabel('评分', fontsize=12)
plt.ylim(0, 100)
plt.tight_layout()
plt.show()

# 水平柱状图
plt.figure(figsize=(10, 6))
plt.barh(categories, values, color=colors)
plt.title('部门评分(水平)', fontsize=16)
plt.xlabel('评分')
plt.tight_layout()
plt.show()

散点图

散点图适合展示两个变量之间的关系。

np.random.seed(42)
n_points = 100
x = np.random.randn(n_points)
y = 2 * x + np.random.randn(n_points) * 0.5
colors = np.random.rand(n_points)
sizes = np.abs(np.random.randn(n_points)) * 200

plt.figure(figsize=(10, 6))
scatter = plt.scatter(x, y, c=colors, s=sizes, alpha=0.6, cmap='viridis')
plt.colorbar(scatter, label='颜色值')

plt.title('变量关系散点图', fontsize=16)
plt.xlabel('变量 X', fontsize=12)
plt.ylabel('变量 Y', fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

饼图

饼图适合展示各部分占总体的比例。

sizes = [35, 25, 20, 15, 5]
labels = ['技术', '市场', '销售', '运营', '其他']
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']
explode = (0.05, 0, 0, 0, 0)

plt.figure(figsize=(8, 8))
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)
plt.title('支出占比', fontsize=16)
plt.tight_layout()
plt.show()

子图布局

subplot允许在同一画布上创建多个图表。

fig, axes = plt.subplots(2, 2, figsize=(12, 10))

x = np.linspace(0, 10, 100)

axes[0, 0].plot(x, np.sin(x), 'b-')
axes[0, 0].set_title('正弦函数')

axes[0, 1].plot(x, np.cos(x), 'r-')
axes[0, 1].set_title('余弦函数')

axes[1, 0].bar(['A', 'B', 'C', 'D'], [3, 7, 2, 5], color='green')
axes[1, 0].set_title('柱状图示例')

axes[1, 1].scatter(np.random.randn(50), np.random.randn(50), alpha=0.6)
axes[1, 1].set_title('散点图示例')

for ax in axes.flat:
    ax.grid(True, alpha=0.3)
    ax.set_xlabel('X轴')
    ax.set_ylabel('Y轴')

plt.suptitle('子图示例', fontsize=16, y=1.02)
plt.tight_layout()
plt.show()

样式与美化

Matplotlib提供丰富的样式定制选项。

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

fig, ax = plt.subplots(figsize=(10, 6))

x = np.linspace(0, 2 * np.pi, 100)
ax.plot(x, np.sin(x), label='sin(x)', linewidth=2)
ax.plot(x, np.cos(x), label='cos(x)', linewidth=2)

ax.fill_between(x, np.sin(x), alpha=0.3)
ax.set_title('三角函数图', fontsize=16)
ax.set_xlabel('X', fontsize=12)
ax.set_ylabel('Y', fontsize=12)
ax.legend(fontsize=12)
ax.annotate('最大值', xy=(np.pi/2, 1), xytext=(np.pi/2 + 1, 0.8),
            arrowprops=dict(arrowstyle='->', color='red'))

plt.tight_layout()
plt.show()

Matplotlib是数据可视化的基础,掌握它将为使用Seaborn、Plotly等高级库打下坚实基础。建议多尝试不同的图表类型和样式配置。