《matplotlib 常用图表绘制》
matplotlib 是 Python 最基础的数据可视化库。本文整理最常用的几种图表:折线图、柱状图、散点图、直方图、饼图,以及子图布局与中文显示问题。
1 基础准备
import numpy as np
import matplotlib.pyplot as plt
中文显示:macOS/Linux 常缺中文字体,需手动设置,见文末「常见问题」。
2 折线图
x = np.arange(0, 24)
y = np.sin(x / 3)
plt.plot(x, y, marker="o", linestyle="--", label="sin")
plt.xlabel("time")
plt.ylabel("value")
plt.title("line plot")
plt.legend() # 显示图例
plt.grid(True) # 网格
plt.show()
3 柱状图
categories = ["A", "B", "C", "D"]
values = [23, 45, 12, 67]
plt.bar(categories, values, color=["#4C72B0"] * 4)
plt.ylabel("count")
plt.title("bar plot")
plt.show()
4 散点图
rng = np.random.default_rng(0)
x = rng.normal(size=200)
y = 2 * x + rng.normal(size=200)
plt.scatter(x, y, alpha=0.6, s=20) # alpha 半透明, s 点大小
plt.xlabel("feature")
plt.ylabel("target")
plt.show()
5 直方图
data = np.random.default_rng(0).normal(size=1000)
plt.hist(data, bins=50, density=True, alpha=0.7)
plt.xlabel("value")
plt.ylabel("density")
plt.title("histogram")
plt.show()
6 饼图
sizes = [30, 25, 20, 25]
labels = ["cat", "dog", "bird", "fish"]
plt.pie(sizes, labels=labels, autopct="%.1f%%", startangle=90)
plt.axis("equal")
plt.show()
7 子图布局
fig, axes = plt.subplots(1, 2, figsize=(10, 4)) # 1 行 2 列
axes[0].plot(x, y)
axes[0].set_title("plot 1")
axes[1].bar(categories, values)
axes[1].set_title("plot 2")
plt.tight_layout() # 自动调整间距
plt.show()
8 保存图片
# 支持 png / pdf / ps / eps / svg 等格式,格式由扩展名推断
plt.savefig(fname="figure.png", dpi=150, bbox_inches="tight")
plt.savefig(fname="figure.svg", format="svg")
9 常见问题
9.1 中文乱码 / 负号显示异常
plt.rcParams["font.sans-serif"] = ["PingFang SC", "SimHei", "Noto Sans CJK SC", "sans-serif"]
plt.rcParams["axes.unicode_minus"] = False # 解决负号显示为方块
9.2 图例不显示
plt.legend() 只能显示带 label= 参数的元素,且需在 plot/bar/scatter 之后调用。
参考文档
阅读 —
·
全站 —