← 返回首页

第8章 · Matplotlib

Python数据可视化

Matplotlib是Python中最流行的数据可视化库,提供了丰富的绘图功能。本章将介绍Matplotlib的基本图表绘制、高级可视化技术以及图片美化方法,帮助您创建专业的数据可视化图表。

学习目标:完成本章后,您将能够使用Matplotlib创建各种基本图表,掌握热力图和箱线图的绘制方法,学会美化图表并添加标注,以及创建词云图和中文本地化词云图。

本章内容概览

基本图表示例

import matplotlib.pyplot as plt
import numpy as np

# 创建示例数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建折线图
plt.figure(figsize=(10, 6))
plt.plot(x, y1, label='sin(x)', color='blue', linewidth=2)
plt.plot(x, y2, label='cos(x)', color='red', linewidth=2)
plt.title('三角函数图像')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

# 创建柱状图
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 33]

plt.figure(figsize=(8, 5))
plt.bar(categories, values, color=['skyblue', 'lightcoral', 'lightgreen', 'gold', 'violet'])
plt.title('柱状图示例')
plt.xlabel('类别')
plt.ylabel('数值')
plt.show()

热力图与箱线图示例

import seaborn as sns
import pandas as pd

# 创建相关性热力图
data = np.random.randn(10, 10)
plt.figure(figsize=(8, 6))
sns.heatmap(data, annot=True, cmap='coolwarm', center=0)
plt.title('相关性热力图')
plt.show()

# 创建箱线图
data_box = [np.random.normal(0, std, 100) for std in range(1, 5)]
plt.figure(figsize=(8, 6))
plt.boxplot(data_box, labels=['Group 1', 'Group 2', 'Group 3', 'Group 4'])
plt.title('箱线图示例')
plt.ylabel('数值')
plt.show()

图片美化与标注示例

# 创建美化后的图表
plt.style.use('seaborn-v0_8')  # 使用seaborn样式

x = np.linspace(0, 10, 100)
y = x ** 2

fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y, linewidth=3, color='#2E86AB', label='y = x²')

# 添加标注
ax.annotate('最大值区域', xy=(8, 64), xytext=(5, 80),
            arrowprops=dict(facecolor='black', shrink=0.05, width=1.5),
            fontsize=12, ha='center')

# 设置标题和标签
ax.set_title('美化后的二次函数图像', fontsize=16, fontweight='bold')
ax.set_xlabel('x值', fontsize=12)
ax.set_ylabel('y值', fontsize=12)
ax.legend(fontsize=12)
ax.grid(True, alpha=0.3)

# 设置背景色
ax.set_facecolor('#F8F9FA')
fig.patch.set_facecolor('white')

plt.tight_layout()
plt.show()

词云图示例

from wordcloud import WordCloud
from PIL import Image
import jieba

# 英文词云图
text = "Python data science machine learning deep learning \
artificial intelligence visualization matplotlib pandas numpy \
programming coding algorithm"

wordcloud = WordCloud(width=800, height=400, 
                      background_color='white',
                      colormap='viridis').generate(text)

plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('英文词云图', fontsize=16)
plt.show()

自定义中文词云图示例

# 中文词云图
chinese_text = "数据科学 人工智能 机器学习 深度学习 自然语言处理 \
计算机视觉 数据分析 数据可视化 Python编程 算法设计 神经网络 \
大数据 云计算 物联网 区块链 数字化转型"

# 使用jieba进行中文分词
text_cut = " ".join(jieba.cut(chinese_text))

# 创建中文词云
wordcloud_cn = WordCloud(width=800, height=400,
                         background_color='white',
                         font_path='simhei.ttf',  # 使用中文字体
                         colormap='plasma',
                         max_words=50).generate(text_cut)

plt.figure(figsize=(10, 5))
plt.imshow(wordcloud_cn, interpolation='bilinear')
plt.axis('off')
plt.title('中文词云图', fontsize=16, fontproperties='SimHei')
plt.show()

导航