IPython widgets结合Plotly开发动态股票工具时图表不显示问题求助
问题原因
- 核心原因:缺少
Output组件捕获ipywidget事件回调的输出。plot_data函数是通过按钮点击、下拉框变更等事件触发的回调,这类回调中执行的fig.show()输出默认不会渲染到JupyterLab的单元格输出区域,必须通过ipywidgets提供的Output组件显式捕获才能正常显示。 - 次要排查点:如果JupyterLab版本和Plotly版本不兼容,需要安装对应Plotly渲染扩展,执行
pip install jupyterlab-plotly即可。 - 冗余代码问题:代码中重复定义了两次
completed_stock方法,第一次的定义会被第二次覆盖,属于无效代码,可删除第一次的定义,不影响运行但属于不规范写法。
修复方案
第一步:新增Output组件相关逻辑
- 导入Output组件:在import部分加入
from ipywidgets import Output - 初始化Output实例:在创建
graph = StockGraph()之后新增一行plot_output = Output() - 修改
plot_data方法,用Output的上下文管理器包裹绘图逻辑,每次绘图前清空旧输出:
def plot_data(self, *args): if start_date.value.year > 1900 and end_date.value.year > 1900: # 清空之前的输出 plot_output.clear_output(wait=True) # 捕获绘图输出到plot_output with plot_output: new_df = pd.DataFrame() # 原来的lines列表是matplotlib时期的遗留代码,可删除 # while self.lines: # item = self.lines.pop() # item.remove() for tick in self.tickers.keys(): df = self.tickers[tick] start = datetime(start_date.value.year, start_date.value.month, start_date.value.day) end = datetime(end_date.value.year, end_date.value.month, end_date.value.day) selection = df.loc[(df.index >= start) & (df.index <= end)] value = self.views[calculation.value](selection[data_type.value]) new_df[tick] = value fig = px.line(new_df, x=new_df.index, y=new_df.columns) fig.show()
- 将Output组件加入最终的布局中,把原来的
final_view定义修改为:
final_view = HBox([ VBox([tickersWidget, dropdowns, dates, rolling],layout=Layout(width='20%')), plot_output ]) display(final_view)
第二步:可选优化(提升渲染性能)
可以改用Plotly的FigureWidget代替普通的Express图表,不用每次生成新图表,直接更新数据即可,交互更流畅,避免反复创建新图表的开销。
内容的提问来源于stack exchange,提问作者Colin99d
相关产品推荐
相关产品推荐

