import numpy as np
import matplotlib.pyplot as plt1 Python
1.1 Matplotlib
1.1.1 绘图逻辑
从一个完整的绘图单位 Figure(画布)开始,其可以包含多个 Axes(坐标系:直角坐标系、极坐标系),这是(堆叠)放置具体 plots(如散点图、曲线图等)的地方,每个 Axes 可以包含 2 个(2D - (x, y) or (theta, r))或 3 个(3D - (x, y, z))Axis,其指代具体的坐标轴。
创建 Figure 和 Axes 的方式:
# an empty figure with no Axes
fig = plt.figure()
# a figure with a single Axes
fig, ax = plt.subplots()
# a figure with NxN grid of Axes
fig, axs = plt.subplots(2, 2)
# a figure with one Axes on the left, and two on the right
# with Axes objects spanning columns or rows
fig, axs = plt.subplot_mosaic([["left", "right_top"], ["left", "right_bottom"]])Matplotlib 提供了两种绘图方式:
- Implicitly create
FigureandAxes:适合快速探索。
Rely on pyplot to implicitly create and manage the Figures and Axes, and use pyplot functions for plotting.
x = np.linspace(0, 2, 100)
# unit is inches
# an empty figure with no Axes
# 后续由 `plt` 负责创建 Axes
plt.figure(figsize=(5, 2.7), layout="constrained")
# plot some data on the implicit Axes
plt.plot(x, x, label="linear")
plt.plot(x, x**2, label="quadratic")
plt.plot(x, x**3, label="cubic")
plt.xlabel("x label")
plt.ylabel("y label")
plt.title("Simple Plot")
plt.legend()- Explicitly create
FigureandAxes:定制 layout。
Explicitly create Figures and Axes, and call methods on them (the “object-oriented (OO) style”).
x = np.linspace(0, 2, 100)
# 显示地创建 Figure 和 Axes
fig, ax = plt.subplots(figsize=(5, 2.7), layout="constrained")
# plot some data on the Axes
ax.plot(x, x, label="linear")
ax.plot(x, x**2, label="quadratic")
ax.plot(x, x**3, label="cubic")
ax.set_xlabel("x label")
ax.set_ylabel("y label")
ax.set_title("Simple Plot")
ax.legend()对于 Maplotlib 的每个 part,需要分清其属于哪个 level - Figure、Axes 和 Axis:
1.2 Seaborn
For making statistical graphics.
import pandas as pd
import numpy as np
import seaborn as sns1.2.1 绘图逻辑
Seaborn 提供两类绘图方案:
- 数据类型驱动的完整的快速数据探索(
Figure-level):
两个连续型变量之间的关系(relational):
sns.relplot()。数据的分布情况(distributional):
sns.displot()。一个离散型变量(分类)与一个连续型变量(统计)(categorical):
sns.catplot()。
- 提供一个个具体的 plot 类型(
Axes-level),你负责将这些 plots 一一添加到指定的Axes中。
