Python 动态交互式数据可视化实战
前言
在数据分析领域,数据可视化是至关重要的一步。优秀的可视化不仅能帮助开发者更深入地理解数据集中的动态变化,还能让后续的机器学习工作更加高效,同时使他人更容易理解数据背后的逻辑。
本文将详细介绍 Python 中最常用的数据可视化库,包括 Matplotlib、Plotly、Bokeh、Seaborn 以及 nbinteract。通过 Iris 数据集和特斯拉股票数据的实际案例,演示如何创建静态图表、3D 动画、交互式时间序列图以及仪表盘组件。
环境准备
在开始之前,请确保已安装以下核心库:
pip install matplotlib seaborn plotly bokeh nbinteract imageio ipywidgets pandas numpy scikit-learn
Matplotlib:基础绘图与动画
Matplotlib 可能是最广为人知的 Python 数据可视化库。它功能强大,适合生成高质量的静态图像,也支持通过 API 制作简单的动画。
1. 3D PCA 方差 GIF 图
我们可以利用 Matplotlib 结合 Seaborn 加载 Iris 数据集并执行主成分分析(PCA)。成功之后,通过从轴上改变不同角度观察,绘制多张 PCA 方差图,最终合成 GIF。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import seaborn as sns
import os
from sklearn.decomposition import PCA
import imageio
# 加载数据集
df = sns.load_dataset('iris')
# 设置 DPI
my_dpi = 96
plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)
# 处理物种列,使其可用于着色
df['species'] = pd.Categorical(df['species'])
my_color = df['species'].cat.codes
df_processed = df.drop('species', axis=1)
# 执行 PCA
pca = PCA(n_components=3)
pca.fit(df_processed)
# 存储结果
result = pd.DataFrame(pca.transform(df_processed),
columns=[, , ],
index=df_processed.index)
angle (, , ):
fig = plt.figure()
ax = fig.add_subplot(, projection=)
ax.scatter(result[], result[], result[],
c=my_color, cmap=, s=)
xAxisLine = (((result[]), (result[])), (, ), (, ))
ax.plot(xAxisLine[], xAxisLine[], xAxisLine[], )
yAxisLine = ((, ), ((result[]), (result[])), (, ))
ax.plot(yAxisLine[], yAxisLine[], yAxisLine[], )
zAxisLine = ((, ), (, ), ((result[]), (result[])))
ax.plot(zAxisLine[], zAxisLine[], zAxisLine[], )
ax.view_init(, angle)
ax.set_xlabel()
ax.set_ylabel()
ax.set_zlabel()
ax.set_title()
filename =
plt.savefig(filename, dpi=)
plt.close(fig)
():
episode_frames = []
time_per_step =
root, _, files os.walk(input_folder):
file_paths = [os.path.join(root, file) file files]
file_paths = (file_paths, key= x: os.path.getmtime(x))
episode_frames = [
imageio.imread(file_path)
file_path file_paths file_path.endswith()
]
episode_frames = np.array(episode_frames)
imageio.mimsave(save_filepath, episode_frames, duration=time_per_step)
make_gif(, )


