Plotly蜡烛图无法显示求助:fig.show()返回空白界面
Plotly蜡烛图显示异常问题排查
问题描述
我用Plotly绘制蜡烛图时遇到以下问题:
- 调用
fig.show()或iplot(fig)后只显示空白界面 - 使用
plt.plot(fig)触发TypeError: unhashable type: 'Figure'错误
代码示例
import plotly.graph_objects as go candlestick_data = data.groupby(data.Date.dt.date).agg({'Price':['min','max','first' ,'last']}) fig = go.Figure(data=[go.Candlestick(x = candlestick_data.index, open=candlestick_data['Price']['first'], high=candlestick_data['Price']['max'], low=candlestick_data['Price']['min'], close=candlestick_data['Price']['last']) ]) fig.update_layout(xaxis_rangeslider_visible=False, xaxis_title='Date', yaxis_title='Price(USD$)', title='Bitcoin Candlestick Chart Over Past 30 Days') fig.show() # 返回空白界面
数据样式
附candlestick_data的数据截图:
解决思路
1. 规范时间索引格式
从截图可见,数据索引是datetime.date类型,Plotly对datetime64格式的时间支持更稳定,建议转换索引类型:
import pandas as pd candlestick_data.index = pd.to_datetime(candlestick_data.index)
2. 检查数据完整性
空白界面大概率是数据存在空值或非数值类型导致的,先排查数据:
# 检查各列空值情况 print(candlestick_data.isnull().sum()) # 检查数据类型 print(candlestick_data.dtypes)
如果有空值,可通过candlestick_data.dropna()删除缺失行,或用candlestick_data.fillna(method='ffill')填充。
3. 修复plt.plot(fig)的错误
plt.plot()是Matplotlib的方法,不能直接传入Plotly的Figure对象,这是报错的根源。如果需要用Matplotlib渲染,需先转换格式:
import matplotlib.pyplot as plt fig_mpl = fig.to_mpl() plt.show()
更推荐使用Plotly原生的fig.show()渲染图表。
4. 切换Plotly渲染后端
若fig.show()仍显示空白,可尝试指定渲染后端:
- 强制用浏览器打开图表:
fig.show(renderer="browser") - Jupyter环境下指定Notebook渲染器:
fig.show(renderer="notebook")
5. 升级Plotly版本
旧版本可能存在兼容性bug,升级到最新版试试:
pip install --upgrade plotly
内容的提问来源于stack exchange,提问作者Sepid
相关产品推荐
相关产品推荐

