如何在Jupyter Notebook中交互式可视化多列Pandas DataFrame?

我有一个包含200+列的Pandas DataFrame,目前使用以下代码绘图:
ranked.plot.line(figsize=(20,10),title='Rank Over Time')
我希望能够一次交互式查看其中一列或多列,理想情况下可追踪线条获取精确数值。请问如何在我的Jupyter Notebook中实现此功能?
实现交互式查看的几种实用方案
1. Plotly Express(推荐:简单高效)
Plotly是专注交互式可视化的工具,原生支持悬停显示精确数值、切换列的显示状态,适配Jupyter环境非常友好。
操作步骤:
- 先安装依赖:
pip install plotly
- 代码示例:
import plotly.express as px # 将宽表转换为Plotly更易处理的长格式 df_long = ranked.reset_index().melt(id_vars='index', var_name='列名', value_name='排名') # 生成交互式折线图 fig = px.line(df_long, x='index', y='排名', color='列名', title='Rank Over Time') fig.update_layout( xaxis_title='时间', yaxis_title='排名', height=600, width=1000 ) fig.show()
交互功能:
- 悬停在任意线条上,可查看当前时间点的列名、排名数值
- 点击图例中的列名,一键切换对应线条的显示/隐藏
- 支持图表缩放、平移、下载导出
2. Bokeh(灵活定制)
Bokeh也是专业交互式可视化库,适合需要自定义交互逻辑的场景。
操作步骤:
- 安装依赖:
pip install bokeh
- 代码示例:
from bokeh.plotting import figure, show, output_notebook from bokeh.models import HoverTool, ColumnDataSource # 配置在Notebook中显示图表 output_notebook() # 构建数据源 source = ColumnDataSource(ranked.reset_index()) # 初始化图表 p = figure(title='Rank Over Time', x_axis_label='时间', y_axis_label='排名', width=1000, height=600) # 遍历所有列绘制线条 for col in ranked.columns: p.line(x='index', y=col, source=source, legend_label=col, line_width=2) # 添加悬停工具,显示精确数值 hover = HoverTool(tooltips=[ ('时间', '@index'), ('排名', '@$name'), ('列名', '$name') ], mode='vline') p.add_tools(hover) # 设置图例可点击切换显示状态 p.legend.click_policy="hide" show(p)
交互功能:
- 垂直悬停线同步显示所有列的当前数值
- 点击图例单独控制单条线条的显示/隐藏
- 自带缩放、平移、框选工具
3. ipywidgets + Matplotlib(适配Matplotlib用户)
如果习惯使用Matplotlib,可以通过ipywidgets添加交互控件,实现列的选择切换,配合Matplotlib的交互式后端实现数值追踪。
操作步骤:
- 安装依赖:
pip install ipywidgets jupyter nbextension enable --py widgetsnbextension
- 代码示例:
# 开启Matplotlib的Notebook交互式后端 %matplotlib notebook import matplotlib.pyplot as plt import ipywidgets as widgets from IPython.display import display # 创建多列选择控件 column_selector = widgets.SelectMultiple( options=ranked.columns.tolist(), value=[ranked.columns[0]], description='选择列:', disabled=False, layout={'height': '200px'} ) # 定义绘图函数 def plot_selected_columns(columns): plt.clf() ranked[list(columns)].plot.line(ax=plt.gca(), title='Rank Over Time', figsize=(20,10)) plt.xlabel('时间') plt.ylabel('排名') plt.tight_layout() # 绑定控件与绘图函数 widgets.interact(plot_selected_columns, columns=column_selector);
交互功能:
- 通过多选框自由选择要展示的列
- 悬停在线条上可查看精确数值(依赖
%matplotlib notebook后端)
内容的提问来源于stack exchange,提问作者hendry
相关产品推荐
相关产品推荐

