Google Colab中ipywidgets交互函数内Plotly图表无法渲染
Plotly + ipywidgets 在Google Colab中切换选项后图表空白的解决办法
问题概述
使用Plotly 5.13.1与ipywidgets 7.7.1在Google Colab开发交互式图表,切换单选按钮选项后,图表区域仅显示空白(已预留空间但无内容)。尝试修改渲染器设置、添加离线初始化函数等方案,仅偶尔生效,未彻底解决问题。
可行解决方案
针对Colab环境的特性,调整代码逻辑与输出方式,具体修改要点如下:
- 替换交互式函数中的
fig.show()为display(fig),避免渲染冲突 - 添加空数据判断,防止无数据时出现空白
- 简化渲染器配置,移除无效的离线初始化代码
- 优化数据筛选逻辑,避免链式索引警告
修改后的完整代码
import plotly.express as px import ipywidgets as widgets import plotly.io as pio from IPython.display import display, HTML # 配置Colab兼容的渲染器 pio.renderers.default = 'colab' def plotfun(Complex_Name, Num_Beds): # 转换输入格式与数据匹配 definer = {'1 Bedroom':'1 bed', '2 Bedroom':'2 beds', '3 Bedroom':'3 beds'} Num_Beds_def = definer.get(Num_Beds) # 筛选数据(使用.loc避免链式索引警告) Complex_df = existing.loc[existing['Complex Name'] == Complex_Name] Complex_df = Complex_df.loc[Complex_df['Number of Bedrooms'] == Num_Beds_def] # 处理无数据情况 if Complex_df.empty: display(HTML(f"<h3>无{Num_Beds}户型的{Complex_Name}数据</h3>")) return # 替换"Call for Rent"为0以便绘图 Complex_df['Unit Prices'] = Complex_df['Unit Prices'].replace(['Call for Rent'], 0) # 生成Plotly图表 fig = px.scatter( Complex_df, x='Date', y='Unit Prices', color='Unit Name', symbol='Unit Name', template='plotly_dark', title=f'<b>{Complex_Name} {Num_Beds} Units</b>', width=1600, height=700, hover_name="Unit Name", hover_data=['Square Feet', 'Unit Prices', 'Availibility Date', 'Number of Bathrooms'] ) # 设置Y轴范围 fig.update_yaxes(range=[1500, 2800]) # 调整图例样式 fig.update_layout( legend=dict( orientation="h", entrywidth=50, yanchor="bottom", y=1.02, xanchor="right", x=1, bgcolor="black", bordercolor="steelblue", borderwidth=0.5 ), yaxis=dict( tickfont=dict(size=14), titlefont=dict(size=18) ) ) # 使用display输出图表,替代fig.show() display(fig) # 创建交互组件 interactive = widgets.interactive( plotfun, Complex_Name=widgets.RadioButtons( options=existing['Complex Name'].unique(), description='小区名称:', disabled=False ), Num_Beds=widgets.RadioButtons( options=['1 Bedroom', '2 Bedroom', '3 Bedroom'], description='卧室数量:', disabled=False ) ) # 布局交互组件 controls = widgets.HBox(interactive.children[:-1], layout=widgets.Layout(flex_flow='row wrap')) output = interactive.children[-1] display(widgets.VBox([controls, output]))
关键修改说明
- 替换
fig.show()为display(fig):在ipywidgets的交互回调中,Colab对fig.show()的渲染支持存在兼容性问题,改用IPython的display()方法能稳定输出图表。 - 添加空数据判断:当选中的小区和户型组合无对应数据时,输出提示信息,避免空白区域。
- 优化数据筛选:使用
.loc方法替代链式索引,避免Pandas的SettingWithCopyWarning,同时保证数据筛选的稳定性。 - 移除无效初始化代码:Colab已内置Plotly的在线渲染支持,无需额外加载require.js或初始化离线模式,仅需配置
pio.renderers.default = 'colab'即可。
内容的提问来源于stack exchange,提问作者Ant
相关产品推荐
相关产品推荐

