装库

pip install matplotlib seaborn

Matplotlib:底层老牌

import matplotlib.pyplot as plt
import numpy as np

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

plt.figure(figsize=(8, 4))
plt.plot(x, y, label="sin(x)")
plt.title("正弦曲线")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.grid(True)
plt.show()

多图

plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.legend()
plt.show()

子图

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].plot(x, np.sin(x))
axes[0].set_title("sin")
axes[1].plot(x, np.cos(x))
axes[1].set_title("cos")
plt.tight_layout()
plt.show()

常见图表

plt.bar(["A", "B", "C"], [10, 20, 15])           # 柱状图
plt.scatter(x, y)                                 # 散点
plt.hist(np.random.randn(1000), bins=30)          # 直方图
plt.pie([30, 20, 50], labels=["A", "B", "C"])     # 饼图
plt.boxplot([data1, data2, data3])                # 箱线图

中文显示(避免乱码)

plt.rcParams["font.sans-serif"] = ["SimHei"]      # Windows
plt.rcParams["font.sans-serif"] = ["PingFang SC"] # Mac
plt.rcParams["axes.unicode_minus"] = False        # 负号

Seaborn:在 Matplotlib 上美化 + 数据集成

import seaborn as sns
import pandas as pd

df = pd.DataFrame({
    "x": np.random.randn(100),
    "y": np.random.randn(100),
    "group": np.random.choice(["A", "B"], 100),
})

# 散点图按 group 着色
sns.scatterplot(data=df, x="x", y="y", hue="group")

# 分布图
sns.histplot(df["x"], kde=True)

# 配对图(多列两两对比)
sns.pairplot(df, hue="group")

# 热力图(相关性矩阵)
sns.heatmap(df.corr(numeric_only=True), annot=True, cmap="coolwarm")

plt.show()

Seaborn 默认皮肤更现代,参数和 DataFrame 友好——做数据探索时优先 Seaborn

保存图片

plt.savefig("chart.png", dpi=300, bbox_inches="tight")

实战:销售数据可视化

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv("sales.csv")

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

# 各地区销售总额
df.groupby("region")["amount"].sum().plot.bar(ax=axes[0, 0], title="地区")

# 时间序列
df["month"] = pd.to_datetime(df["date"]).dt.month
df.groupby("month")["amount"].sum().plot(ax=axes[0, 1], title="月度")

# 分布
sns.histplot(df["amount"], ax=axes[1, 0], kde=True)
axes[1, 0].set_title("订单金额分布")

# 散点
sns.scatterplot(data=df, x="quantity", y="amount", hue="region", ax=axes[1, 1])

plt.tight_layout()
plt.savefig("dashboard.png", dpi=150)

现代替代:Plotly

pip install plotly
import plotly.express as px
fig = px.scatter(df, x="x", y="y", color="group")
fig.show()

Plotly 输出交互式 HTML——可以悬停、缩放。做仪表板优先 Plotly。

下一篇讲 scikit-learn——经典 ML 一文上手。