Plot
matplotlib导入
import matplotlib.pyplot as plt
import seaborn as sns
导入绘图库:matplotlib 用于基础绘图,seaborn 用于更美观和统计型绘图。
设置全局的图表属性
plt.rc(
"figure",
autolayout=True,
figsize=(11, 4),
titlesize=18,
titleweight='bold',
)
自动布局(避免标题或标签被裁掉)
图大小:11 x 4 英寸
标题字体大小 18,粗体
设置坐标轴样式
plt.rc(
"axes",
labelweight="bold",
labelsize="large",
titleweight="bold",
titlesize=16,
titlepad=10,
)
- 标签粗体、字号大
- 坐标轴标题粗体,字号 16,和轴之间的间距 10
在 Jupyter Notebook 里用高清渲染
%config InlineBackend.figure_format = 'retina'
作图
fig, ax = plt.subplots()
ax.plot('Time', 'Hardcover', data=df, color='0.75')
-
建立一个子图
ax。 -
使用 折线图 画出时间 (
Time) 与销量 (Hardcover) 的趋势。 -
color='0.75'→ 灰色线条。
设置标题
ax.set_title('Time Plot of Hardcover Sales');
设置坐标轴比例
ax.set_aspect('equal')
设置坐标轴比例为 1:1,确保横纵方向缩放一致。
在滞后图中这样做很有意义,因为理想情况下,如果今天销量和昨天完全相同,点会分布在 对角线 上。
参数
plot_params = dict(
color="0.75",
style=".-",
markeredgecolor="0.25",
markerfacecolor="0.25",
legend=False,
)
ax = y.plot(**plot_params)
plot_params 是一些绘图参数,方便之后直接传递给 plot()。
点阵图
ax = tunnel.plot(style=".", color="0.5")
无legend,线宽
moving_average.plot(
ax=ax, linewidth=3, title="Tunnel Traffic - 365-Day Moving Average", legend=False,
)
seaborn
样式
import seaborn as sns
print(plt.style.available)
plt.style.use("seaborn-v0_8-whitegrid")
看看可用的样式,使用 seaborn 的白色网格风格,让图表更清晰。
回归散点图
sns.regplot(x='Time', y='Hardcover', data=df, ci=None, scatter_kws=dict(color='0.25'), ax=ax)
用 seaborn 的 回归散点图(regplot)覆盖在上面:
- 横轴
Time,纵轴Hardcover ci=None关闭置信区间scatter_kws=dict(color='0.25')→ 点的颜色深灰- 回归线展示销量随时间的整体趋势