数据可视化实战
用 matplotlib 和 seaborn 把数据变成图表——从基础绑图到仪表盘,一页入门数据可视化。
可视化工具选择
graph TD
VIZ[Python 可视化] --> STATIC[静态图表]
VIZ --> INTER[交互图表]
VIZ --> DASH[仪表盘]
STATIC --> MPL[matplotlib]
STATIC --> SNS[seaborn]
INTER --> PLOTLY[plotly]
INTER --> BOKEH[bokeh]
DASH --> STREAM[Streamlit]
DASH --> GRADIO[Gradio]
MPL --> M1[最灵活 底层控制]
SNS --> S1[统计图表 美观]
PLOTLY --> P1[交互 网页嵌入]
style VIZ fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
style SNS fill:#c8e6c9,stroke:#388e3c,stroke-width:2px
matplotlib 基础
"""
matplotlib:最灵活的绑图库
"""
import matplotlib.pyplot as plt
import numpy as np
# === 基础线图 ===
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(x, y1, label="sin(x)", color="#1565c0", linewidth=2)
ax.plot(x, y2, label="cos(x)", color="#c62828", linewidth=2, linestyle="--")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("三角函数")
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("trig.png", dpi=150)
plt.close()
# === 常用图表类型 ===
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# 柱状图
categories = ["Python", "JS", "Rust", "Go", "Java"]
values = [92, 85, 78, 75, 70]
axes[0, 0].bar(categories, values, color="#1565c0")
axes[0, 0].set_title("编程语言满意度")
# 散点图
np.random.seed(42)
x = np.random.randn(100)
y = x * 2 + np.random.randn(100) * 0.5
axes[0, 1].scatter(x, y, alpha=0.6, c=y, cmap="coolwarm")
axes[0, 1].set_title("相关性散点图")
# 饼图
langs = ["Python", "JS", "Java", "其他"]
shares = [35, 25, 20, 20]
axes[1, 0].pie(shares, labels=langs, autopct="%1.0f%%", startangle=90)
axes[1, 0].set_title("语言使用占比")
# 直方图
data = np.random.normal(170, 10, 1000)
axes[1, 1].hist(data, bins=30, color="#388e3c", alpha=0.7, edgecolor="white")
axes[1, 1].set_title("身高分布")
axes[1, 1].axvline(170, color="red", linestyle="--", label="均值")
axes[1, 1].legend()
plt.tight_layout()
plt.savefig("charts.png", dpi=150)
plt.close()
seaborn 统计图表
"""
seaborn:基于 matplotlib 的统计可视化
"""
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# 设置风格
sns.set_theme(style="whitegrid", palette="deep")
# 示例数据
df = pd.DataFrame({
"月份": ["1月", "2月", "3月", "4月", "5月", "6月"] * 3,
"销售额": [100, 120, 115, 130, 145, 160,
80, 95, 90, 110, 120, 135,
60, 70, 85, 90, 100, 110],
"产品": ["A"] * 6 + ["B"] * 6 + ["C"] * 6,
})
# 折线图(按产品分组)
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
sns.lineplot(data=df, x="月份", y="销售额", hue="产品", marker="o", ax=axes[0])
axes[0].set_title("月度销售趋势")
# 箱线图
sns.boxplot(data=df, x="产品", y="销售额", ax=axes[1])
axes[1].set_title("销售额分布")
plt.tight_layout()
plt.savefig("seaborn_charts.png", dpi=150)
plt.close()
# === 热力图 ===
corr_data = pd.DataFrame(
np.random.randn(6, 6),
columns=["特征A", "特征B", "特征C", "特征D", "特征E", "特征F"],
)
corr_matrix = corr_data.corr()
plt.figure(figsize=(8, 6))
sns.heatmap(corr_matrix, annot=True, fmt=".2f", cmap="RdYlBu_r", center=0)
plt.title("特征相关性热力图")
plt.tight_layout()
plt.savefig("heatmap.png", dpi=150)
plt.close()
Streamlit 快速仪表盘
"""
Streamlit:几行代码搭建数据仪表盘
pip install streamlit
streamlit run dashboard.py
"""
DASHBOARD_CODE = '''
import streamlit as st
import pandas as pd
import plotly.express as px
st.set_page_config(page_title="销售仪表盘", layout="wide")
st.title("📊 销售数据仪表盘")
# 侧边栏过滤器
with st.sidebar:
date_range = st.date_input("日期范围", [])
product = st.multiselect("产品", ["A", "B", "C"], default=["A", "B"])
# KPI 指标
col1, col2, col3 = st.columns(3)
col1.metric("总销售额", "¥128,500", "+12%")
col2.metric("订单数", "1,234", "+5%")
col3.metric("客单价", "¥104.2", "-2%")
# 图表
df = pd.DataFrame({
"月份": range(1, 13),
"销售额": [100, 120, 115, 130, 145, 160, 155, 170, 180, 175, 190, 200],
})
fig = px.line(df, x="月份", y="销售额", title="月度销售趋势")
st.plotly_chart(fig, use_container_width=True)
'''
print("运行: streamlit run dashboard.py")
工具对比
| 工具 | 类型 | 学习曲线 | 美观度 | 交互性 | 推荐场景 |
|---|---|---|---|---|---|
| matplotlib | 静态 | 中 | 中 | 无 | 精确控制 |
| seaborn | 静态 | 低 | 高 | 无 | 统计图表 |
| plotly | 交互 | 低 | 高 | 强 | 网页嵌入 |
| Streamlit | 仪表盘 | 极低 | 高 | 强 | 快速原型 |
| bokeh | 交互 | 中 | 中 | 强 | 大数据集 |
本章小结
| 知识点 | 要点 |
|---|---|
| matplotlib | fig + ax 对象式绑图、savefig 导出 |
| seaborn | set_theme 风格、heatmap 热力图 |
| plotly | px 快速绑图、交互式 |
| Streamlit | st.metric + st.plotly_chart |
下一章:Web 开发——FastAPI 入门与实战。