返回文章列表

Matplotlib数据可视化教程

数据可视化是数据分析中不可或缺的一环。Matplotlib是Python中最经典、最常用的绘图库,能够创建出版质量的图表。本教程将从基础到进阶,带你全面掌握Matplotlib的使用方法。

一、Matplotlib简介与安装

Matplotlib是一个用于创建静态、动态和交互式可视化的Python库。它的设计灵感来自MATLAB的绘图功能,因此得名"Matplotlib"。

安装

# 安装matplotlib
pip install matplotlib

# 安装matplotlib和numpy(通常一起使用)
pip install matplotlib numpy

第一个图表

# first_plot.py - 第一个Matplotlib图表
import matplotlib.pyplot as plt

# 准备数据
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# 绘制折线图
plt.plot(x, y)

# 设置标题和标签
plt.title("我的第一个图表")
plt.xlabel("X轴")
plt.ylabel("Y轴")

# 显示图表
plt.show()

如果是在Jupyter Notebook中使用,需要添加魔术命令:

%matplotlib inline

二、Figure与Axes

理解Matplotlib的绘图体系非常重要。Matplotlib的图表由两个核心对象组成:

# figure_axes.py - Figure和Axes详解
import matplotlib.pyplot as plt
import numpy as np

# ===== 方式1:面向过程(pyplot接口) =====
plt.figure(figsize=(8, 5))  # 创建Figure
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("pyplot接口")
plt.show()

# ===== 方式2:面向对象(推荐) =====
fig, ax = plt.subplots(figsize=(8, 5))  # 同时创建Figure和Axes
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title("面向对象接口")
plt.show()

# ===== 方式3:创建多个子图 =====
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# axes是一个2x2的Axes数组

# 在第一个子图绘制折线图
axes[0, 0].plot([1, 2, 3], [1, 4, 9])
axes[0, 0].set_title("子图1: 折线图")

# 在第二个子图绘制柱状图
axes[0, 1].bar(['A', 'B', 'C'], [10, 20, 15])
axes[0, 1].set_title("子图2: 柱状图")

# 在第三个子图绘制散点图
axes[1, 0].scatter([1, 2, 3, 4], [10, 20, 15, 25])
axes[1, 0].set_title("子图3: 散点图")

# 在第四个子图绘制饼图
axes[1, 1].pie([30, 40, 30], labels=['A', 'B', 'C'])
axes[1, 1].set_title("子图4: 饼图")

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

三、折线图(plot)

折线图是最基本的图表类型,适合展示数据随时间或顺序的变化趋势。

# line_chart.py - 折线图示例
import matplotlib.pyplot as plt
import numpy as np

# 创建模拟数据:12个月的销售额(万元)
months = ['1月', '2月', '3月', '4月', '5月', '6月',
          '7月', '8月', '9月', '10月', '11月', '12月']
sales_2024 = [45, 52, 48, 61, 55, 72, 68, 80, 75, 88, 92, 105]
sales_2023 = [38, 42, 40, 50, 48, 58, 55, 65, 60, 72, 78, 85]

# 创建图表
fig, ax = plt.subplots(figsize=(12, 6))

# 绘制两条折线
ax.plot(months, sales_2024, marker='o', linewidth=2, markersize=6,
        color='#2196F3', label='2024年')
ax.plot(months, sales_2023, marker='s', linewidth=2, markersize=6,
        color='#FF9800', label='2023年', linestyle='--')

# 设置标题和标签
ax.set_title('月度销售额趋势对比', fontsize=16, fontweight='bold')
ax.set_xlabel('月份', fontsize=12)
ax.set_ylabel('销售额(万元)', fontsize=12)

# 添加网格线
ax.grid(True, alpha=0.3)

# 添加图例
ax.legend(fontsize=12)

# 旋转x轴标签
plt.xticks(rotation=45)

# 添加数据标注(标注最大值)
max_idx = sales_2024.index(max(sales_2024))
ax.annotate(f'最高: {sales_2024[max_idx]}万',
            xy=(months[max_idx], sales_2024[max_idx]),
            xytext=(10, 20), textcoords='offset points',
            arrowprops=dict(arrowstyle='->', color='red'),
            fontsize=10, color='red')

plt.tight_layout()
plt.savefig('line_chart.png', dpi=150, bbox_inches='tight')
plt.show()

四、柱状图(bar)

柱状图适合比较不同类别之间的数据差异。

# bar_chart.py - 柱状图示例
import matplotlib.pyplot as plt
import numpy as np

# 各编程语言流行度数据
languages = ['Python', 'JavaScript', 'Java', 'C++', 'Go', 'Rust', 'TypeScript']
popularity_2024 = [28.1, 18.0, 15.6, 10.3, 8.2, 5.1, 4.8]
popularity_2023 = [27.5, 17.2, 16.0, 11.2, 7.5, 3.8, 3.5]

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

# 设置柱子宽度
x = np.arange(len(languages))
bar_width = 0.35

# 绘制分组柱状图
bars1 = ax.bar(x - bar_width/2, popularity_2023, bar_width,
               label='2023年', color='#4CAF50', alpha=0.8)
bars2 = ax.bar(x + bar_width/2, popularity_2024, bar_width,
               label='2024年', color='#2196F3', alpha=0.8)

# 在柱子上添加数值标签
for bar in bars1:
    height = bar.get_height()
    ax.annotate(f'{height}%',
                xy=(bar.get_x() + bar.get_width() / 2, height),
                xytext=(0, 3), textcoords="offset points",
                ha='center', va='bottom', fontsize=9)

for bar in bars2:
    height = bar.get_height()
    ax.annotate(f'{height}%',
                xy=(bar.get_x() + bar.get_width() / 2, height),
                xytext=(0, 3), textcoords="offset points",
                ha='center', va='bottom', fontsize=9)

# 设置标题和标签
ax.set_title('编程语言流行度对比(%)', fontsize=16, fontweight='bold')
ax.set_xlabel('编程语言', fontsize=12)
ax.set_ylabel('流行度指数(%)', fontsize=12)
ax.set_xticks(x)
ax.set_xticklabels(languages)
ax.legend(fontsize=12)
ax.grid(axis='y', alpha=0.3)

plt.tight_layout()
plt.savefig('bar_chart.png', dpi=150, bbox_inches='tight')
plt.show()

五、散点图(scatter)

散点图用于展示两个变量之间的关系,常用于相关性分析和聚类分析。

# scatter_plot.py - 散点图示例
import matplotlib.pyplot as plt
import numpy as np

# 生成模拟数据:学习时间 vs 考试成绩
np.random.seed(42)
study_hours = np.random.uniform(1, 10, 50)  # 学习时间(小时)
exam_scores = 40 + study_hours * 5 + np.random.normal(0, 8, 50)  # 考试成绩
exam_scores = np.clip(exam_scores, 0, 100)  # 限制在0-100范围

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

# 绘制散点图,颜色表示学习时间
scatter = ax.scatter(study_hours, exam_scores, c=study_hours,
                     cmap='RdYlGn', s=80, alpha=0.7, edgecolors='gray')

# 添加颜色条
cbar = plt.colorbar(scatter)
cbar.set_label('学习时间(小时)', fontsize=11)

# 添加趋势线
z = np.polyfit(study_hours, exam_scores, 1)
p = np.poly1d(z)
x_line = np.linspace(1, 10, 100)
ax.plot(x_line, p(x_line), '--', color='red', linewidth=2,
        label=f'趋势线 (y={z[0]:.1f}x+{z[1]:.1f})')

# 设置标题和标签
ax.set_title('学习时间与考试成绩的关系', fontsize=16, fontweight='bold')
ax.set_xlabel('学习时间(小时)', fontsize=12)
ax.set_ylabel('考试成绩(分)', fontsize=12)
ax.legend(fontsize=12)
ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.savefig('scatter_plot.png', dpi=150, bbox_inches='tight')
plt.show()

六、饼图(pie)

饼图适合展示各部分在整体中所占的比例。

# pie_chart.py - 饼图示例
import matplotlib.pyplot as plt

# 网站流量来源数据
sources = ['直接访问', '搜索引擎', '社交媒体', '外部链接', '邮件营销', '其他']
traffic = [35, 28, 18, 10, 6, 3]
colors = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#C9CBCF']
explode = (0.05, 0.08, 0, 0, 0, 0)  # 突出显示前两个

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

# 绘制饼图
wedges, texts, autotexts = ax.pie(
    traffic,
    labels=sources,
    colors=colors,
    explode=explode,
    autopct='%1.1f%%',
    startangle=90,
    pctdistance=0.75,
    shadow=False
)

# 设置字体样式
for text in texts:
    text.set_fontsize(12)
for autotext in autotexts:
    autotext.set_fontsize(10)
    autotext.set_color('white')
    autotext.set_fontweight('bold')

# 添加中心空白,制作环形图
centre_circle = plt.Circle((0, 0), 0.50, fc='white')
ax.add_artist(centre_circle)

# 在中心添加文字
ax.text(0, 0.05, '流量', ha='center', va='center', fontsize=16, fontweight='bold')
ax.text(0, -0.1, '来源', ha='center', va='center', fontsize=14)

ax.set_title('网站流量来源分布', fontsize=16, fontweight='bold', pad=20)

plt.tight_layout()
plt.savefig('pie_chart.png', dpi=150, bbox_inches='tight')
plt.show()

七、直方图(hist)

直方图用于展示数据的分布情况,常用于统计分析。

# histogram.py - 直方图示例
import matplotlib.pyplot as plt
import numpy as np

# 模拟学生考试成绩数据
np.random.seed(42)
scores = np.concatenate([
    np.random.normal(65, 10, 200),   # 大部分学生分数在65分左右
    np.random.normal(85, 8, 50),     # 一部分高分学生
    np.random.normal(45, 12, 30)     # 少数低分学生
])
scores = np.clip(scores, 0, 100)

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

# 绘制直方图
n, bins, patches = ax.hist(scores, bins=20, color='#3498DB',
                            edgecolor='white', alpha=0.8, density=True)

# 根据分数区间给柱子上色
for i, patch in enumerate(patches):
    bin_center = (bins[i] + bins[i+1]) / 2
    if bin_center < 60:
        patch.set_facecolor('#E74C3C')  # 红色:不及格
    elif bin_center < 80:
        patch.set_facecolor('#F39C12')  # 橙色:良好
    else:
        patch.set_facecolor('#27AE60')  # 绿色:优秀

# 添加统计信息
mean_score = np.mean(scores)
median_score = np.median(scores)
ax.axvline(mean_score, color='red', linestyle='--', linewidth=2,
           label=f'平均分: {mean_score:.1f}')
ax.axvline(median_score, color='blue', linestyle=':', linewidth=2,
           label=f'中位数: {median_score:.1f}')

ax.set_title('学生考试成绩分布', fontsize=16, fontweight='bold')
ax.set_xlabel('分数', fontsize=12)
ax.set_ylabel('概率密度', fontsize=12)
ax.legend(fontsize=12)
ax.grid(axis='y', alpha=0.3)

plt.tight_layout()
plt.savefig('histogram.png', dpi=150, bbox_inches='tight')
plt.show()

八、子图与布局(subplots)

在一个Figure中创建多个子图是常见的需求。Matplotlib提供了灵活的布局管理方式。

# subplots_demo.py - 子图布局示例
import matplotlib.pyplot as plt
import numpy as np

# 准备共享数据
x = np.linspace(0, 10, 100)

# 创建2行2列子图,共享x轴
fig, axes = plt.subplots(2, 2, figsize=(12, 10), sharex=True)

# 子图1:折线图
axes[0, 0].plot(x, np.sin(x), color='#2196F3', linewidth=2, label='sin(x)')
axes[0, 0].plot(x, np.cos(x), color='#FF5722', linewidth=2, label='cos(x)')
axes[0, 0].set_title('三角函数', fontweight='bold')
axes[0, 0].legend()
axes[0, 0].grid(True, alpha=0.3)

# 子图2:面积图
axes[0, 1].fill_between(x, np.sin(x), alpha=0.3, color='#4CAF50')
axes[0, 1].fill_between(x, np.sin(x) + 1, alpha=0.3, color='#2196F3')
axes[0, 1].set_title('面积图', fontweight='bold')
axes[0, 1].grid(True, alpha=0.3)

# 子图3:柱状图
categories = ['A', 'B', 'C', 'D', 'E']
values = np.random.randint(10, 50, size=5)
colors = ['#E74C3C', '#3498DB', '#2ECC71', '#F39C12', '#9B59B6']
axes[1, 0].barh(categories, values, color=colors, edgecolor='white')
axes[1, 0].set_title('水平柱状图', fontweight='bold')
for i, v in enumerate(values):
    axes[1, 0].text(v + 0.5, i, str(v), va='center', fontweight='bold')

# 子图4:阶梯图
y_step = np.cumsum(np.random.randn(100))
axes[1, 1].step(x, y_step, where='mid', color='#E91E63', linewidth=1.5)
axes[1, 1].fill_between(x, y_step, step='mid', alpha=0.2, color='#E91E63')
axes[1, 1].set_title('阶梯图(累积随机游走)', fontweight='bold')
axes[1, 1].grid(True, alpha=0.3)

# 设置总标题
fig.suptitle('Matplotlib子图布局示例', fontsize=18, fontweight='bold', y=1.02)
plt.tight_layout()
plt.savefig('subplots_demo.png', dpi=150, bbox_inches='tight')
plt.show()

九、样式与颜色定制

Matplotlib提供了丰富的样式和颜色选项,让你的图表更加美观。

# style_demo.py - 样式定制示例
import matplotlib.pyplot as plt
import numpy as np

# ===== 使用内置样式 =====
# 查看所有可用样式
print("可用样式:", plt.style.available)

# ===== 使用自定义样式的完整示例 =====
# 设置全局样式
plt.style.use('seaborn-v0_8-whitegrid')

fig, axes = plt.subplots(1, 3, figsize=(16, 5))

# 自定义颜色方案
custom_colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']

# 图表1:使用自定义颜色绘制
data = np.random.randn(1000)
axes[0].hist(data, bins=30, color=custom_colors[0], alpha=0.7, edgecolor='white')
axes[0].set_title('自定义颜色', fontweight='bold')

# 图表2:使用渐变色
x = np.linspace(0, 10, 100)
for i in range(5):
    y = np.sin(x + i) * (i + 1) / 5
    axes[1].plot(x, y, color=plt.cm.viridis(i / 4), linewidth=2,
                label=f'第{i+1}组')
axes[1].set_title('使用colormap渐变', fontweight='bold')
axes[1].legend()

# 图表3:自定义字体和网格
categories = ['产品A', '产品B', '产品C', '产品D', '产品E']
values = [85, 72, 90, 65, 78]
bars = axes[2].bar(categories, values, color=custom_colors, edgecolor='white',
                   linewidth=1.5)
axes[2].set_title('自定义样式综合', fontweight='bold')
axes[2].set_ylim(0, 110)

# 设置背景色和网格样式
axes[2].set_facecolor('#f8f9fa')
axes[2].grid(axis='y', linestyle='--', alpha=0.5)

plt.tight_layout()
plt.savefig('style_demo.png', dpi=150, bbox_inches='tight')
plt.show()

十、保存图表

# save_fig.py - 保存图表
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])

# 保存为PNG(最常用)
plt.savefig('chart.png', dpi=300, bbox_inches='tight', transparent=False)

# 保存为SVG(矢量图,适合论文和文档)
plt.savefig('chart.svg', format='svg', bbox_inches='tight')

# 保存为PDF(矢量图,适合打印)
plt.savefig('chart.pdf', format='pdf', bbox_inches='tight')

# 保存时设置透明背景
plt.savefig('chart_transparent.png', dpi=300, transparent=True)

# 保存时设置特定尺寸
plt.savefig('chart_wide.png', dpi=150, figsize=(16, 9),
            bbox_inches='tight')

plt.close()  # 关闭Figure释放内存

十一、实战案例:销售数据可视化看板

综合运用以上知识,我们来创建一个完整的销售数据可视化看板。

# sales_dashboard.py - 销售数据可视化看板
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec

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

# ========== 准备数据 ==========
months = ['1月', '2月', '3月', '4月', '5月', '6月',
          '7月', '8月', '9月', '10月', '11月', '12月']

# 月度销售数据(万元)
sales_data = {
    '2024年': [45, 52, 48, 61, 55, 72, 68, 80, 75, 88, 92, 105],
    '2023年': [38, 42, 40, 50, 48, 58, 55, 65, 60, 72, 78, 85]
}

# 产品分类销售占比
product_categories = {
    '电子产品': 35,
    '服装鞋帽': 22,
    '食品饮料': 18,
    '家居用品': 15,
    '图书文具': 10
}

# 各区域销售额
regions = ['华东', '华南', '华北', '西南', '华中', '东北']
region_sales = [320, 280, 250, 180, 150, 120]

# 月度用户增长
new_users = [1200, 1500, 1350, 1800, 1650, 2100,
             1950, 2400, 2200, 2650, 2800, 3100]

# ========== 创建画布 ==========
fig = plt.figure(figsize=(20, 14))
fig.suptitle('2024年度销售数据看板', fontsize=24, fontweight='bold', y=0.98)

# 使用GridSpec实现复杂布局
gs = GridSpec(3, 4, figure=fig, hspace=0.35, wspace=0.3)

# ===== 1. 销售趋势折线图(占2列) =====
ax1 = fig.add_subplot(gs[0, :2])
ax1.plot(months, sales_data['2024年'], marker='o', linewidth=2.5,
         markersize=8, color='#2196F3', label='2024年', zorder=5)
ax1.plot(months, sales_data['2023年'], marker='s', linewidth=2,
         markersize=7, color='#FF9800', label='2023年', linestyle='--', zorder=5)
ax1.fill_between(months, sales_data['2024年'], alpha=0.1, color='#2196F3')
ax1.set_title('月度销售趋势', fontsize=14, fontweight='bold', pad=10)
ax1.set_ylabel('销售额(万元)', fontsize=11)
ax1.legend(fontsize=11, loc='upper left')
plt.setp(ax1.xaxis.get_majorticklabels(), rotation=30)

# ===== 2. 产品分类饼图 =====
ax2 = fig.add_subplot(gs[0, 2])
colors_pie = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF']
wedges, texts, autotexts = ax2.pie(
    product_categories.values(),
    labels=product_categories.keys(),
    colors=colors_pie,
    autopct='%1.1f%%',
    startangle=90,
    pctdistance=0.75
)
ax2.set_title('产品分类占比', fontsize=14, fontweight='bold', pad=10)

# ===== 3. 核心指标卡片区域 =====
ax3 = fig.add_subplot(gs[0, 3])
ax3.axis('off')
total_2024 = sum(sales_data['2024年'])
total_2023 = sum(sales_data['2023年'])
growth_rate = (total_2024 - total_2023) / total_2023 * 100

metrics = [
    ('年度总销售额', f'{total_2024}万', '#2196F3'),
    ('同比增长', f'+{growth_rate:.1f}%', '#4CAF50'),
    ('月均销售额', f'{total_2024/12:.0f}万', '#FF9800'),
    ('峰值月份', f'12月({max(sales_data["2024年"])}万)', '#9C27B0'),
]
for i, (label, value, color) in enumerate(metrics):
    y_pos = 0.85 - i * 0.25
    ax3.text(0.1, y_pos, label, fontsize=11, color='gray',
             transform=ax3.transAxes, va='center')
    ax3.text(0.1, y_pos - 0.1, value, fontsize=18, fontweight='bold',
             color=color, transform=ax3.transAxes, va='center')
ax3.set_title('核心指标', fontsize=14, fontweight='bold', pad=10)

# ===== 4. 区域销售柱状图 =====
ax4 = fig.add_subplot(gs[1, :2])
sorted_data = sorted(zip(regions, region_sales), key=lambda x: x[1])
region_sorted, sales_sorted = zip(*sorted_data)
bars = ax4.barh(region_sorted, sales_sorted, color=plt.cm.Blues(
    np.linspace(0.3, 0.9, len(regions))), edgecolor='white')
for bar in bars:
    width = bar.get_width()
    ax4.text(width + 5, bar.get_y() + bar.get_height()/2,
             f'{width}万', va='center', fontsize=10, fontweight='bold')
ax4.set_title('各区域销售额排名', fontsize=14, fontweight='bold', pad=10)
ax4.set_xlabel('销售额(万元)', fontsize=11)
ax4.set_xlim(0, max(region_sales) * 1.2)

# ===== 5. 用户增长趋势 =====
ax5 = fig.add_subplot(gs[1, 2:])
ax5.bar(months, new_users, color='#4CAF50', alpha=0.7, edgecolor='white')
ax5.plot(months, new_users, color='#E91E63', linewidth=2, marker='D',
         markersize=5, zorder=5)
ax5.fill_between(range(len(months)), new_users, alpha=0.1, color='#4CAF50')
avg_users = np.mean(new_users)
ax5.axhline(avg_users, color='red', linestyle='--', linewidth=1.5,
            label=f'月均新增: {avg_users:.0f}')
ax5.set_title('月度新增用户趋势', fontsize=14, fontweight='bold', pad=10)
ax5.set_ylabel('新增用户数', fontsize=11)
ax5.legend(fontsize=10)
plt.setp(ax5.xaxis.get_majorticklabels(), rotation=30)

# ===== 6. 季度对比柱状图 =====
ax6 = fig.add_subplot(gs[2, :2])
q1_24 = sum(sales_data['2024年'][0:3])
q2_24 = sum(sales_data['2024年'][3:6])
q3_24 = sum(sales_data['2024年'][6:9])
q4_24 = sum(sales_data['2024年'][9:12])
q1_23 = sum(sales_data['2023年'][0:3])
q2_23 = sum(sales_data['2023年'][3:6])
q3_23 = sum(sales_data['2023年'][6:9])
q4_23 = sum(sales_data['2023年'][9:12])

quarters = ['Q1', 'Q2', 'Q3', 'Q4']
quarterly_2024 = [q1_24, q2_24, q3_24, q4_24]
quarterly_2023 = [q1_23, q2_23, q3_23, q4_23]

x_q = np.arange(len(quarters))
ax6.bar(x_q - 0.17, quarterly_2023, 0.3, label='2023年',
        color='#FF9800', alpha=0.8)
ax6.bar(x_q + 0.17, quarterly_2024, 0.3, label='2024年',
        color='#2196F3', alpha=0.8)
for i, (v23, v24) in enumerate(zip(quarterly_2023, quarterly_2024)):
    ax6.text(i - 0.17, v23 + 2, f'{v23}万', ha='center', fontsize=9)
    ax6.text(i + 0.17, v24 + 2, f'{v24}万', ha='center', fontsize=9)
ax6.set_xticks(x_q)
ax6.set_xticklabels(quarters)
ax6.set_title('季度销售额对比', fontsize=14, fontweight='bold', pad=10)
ax6.set_ylabel('销售额(万元)', fontsize=11)
ax6.legend(fontsize=11)

# ===== 7. 同比增长率 =====
ax7 = fig.add_subplot(gs[2, 2:])
monthly_growth = [(v24 - v23) / v23 * 100
                  for v23, v24 in zip(sales_data['2023年'], sales_data['2024年'])]
colors_growth = ['#4CAF50' if g > 0 else '#F44336' for g in monthly_growth]
ax7.bar(months, monthly_growth, color=colors_growth, alpha=0.7, edgecolor='white')
for i, v in enumerate(monthly_growth):
    ax7.text(i, v + 0.3 if v > 0 else v - 1.5,
             f'{v:.1f}%', ha='center', fontsize=9, fontweight='bold')
ax7.axhline(0, color='black', linewidth=0.8)
ax7.set_title('月度同比增长率', fontsize=14, fontweight='bold', pad=10)
ax7.set_ylabel('增长率(%)', fontsize=11)
plt.setp(ax7.xaxis.get_majorticklabels(), rotation=30)

# 保存和显示
plt.savefig('sales_dashboard.png', dpi=150, bbox_inches='tight',
            facecolor='white')
plt.show()
print("销售看板已生成并保存为 sales_dashboard.png")

总结

本教程涵盖了Matplotlib的核心知识:

  1. 了解了Figure和Axes的概念以及面向对象的绘图方式
  2. 学会了折线图、柱状图、散点图、饼图、直方图等常用图表
  3. 掌握了子图布局和GridSpec高级布局
  4. 学习了样式定制和颜色方案
  5. 通过销售看板实战综合运用了多种图表类型

进阶建议:

动手挑战

学到这里,不妨动手试一试以下练习,巩固你的理解:

  1. 基础练习:回顾本文核心概念,用自己的话总结关键知识点。
  2. 进阶实践:将文中的示例代码运行一遍,尝试修改参数观察变化。
  3. 拓展思考:想一想这个技术/方法还能应用在哪些场景中?

小贴士:遇到问题时,先独立思考,再查阅资料,最后请教他人——这是成长最快的学习方式。

赞赏支持

本文更新于 2026-08-22,环境 Python 3.12