Jupyter中使用Plotly报错:plotly.tools无set_credentials_file属性
Plotly中AttributeError: 'plotly.tools' has no attribute 'set_credentials_file'解决方法
问题场景
在Jupyter中跟随Plotly入门教程学习,运行以下代码时出现错误:
import numpy as np import pandas as pd import cufflinks as cf import chart_studio.plotly as py import plotly.tools as tls import plotly.graph_objs as go tls.set_credentials_file(username = "xxx", api_key = "yyyy")
报错信息:
-------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[21], line 1 ----> 1 tls.set_credentials_file(username = "xxxx", api_key = "yyy") AttributeError: module 'plotly.tools' has no attribute 'set_credentials_file'
Stack Overflow上查到的相关问题均为多年前的内容,推测Plotly文档已更新,需要适配新版API的解决方法。
解决方法
- 核心原因:Plotly版本迭代后,
set_credentials_file方法已从plotly.tools迁移至chart_studio.tools模块,旧教程的代码路径已失效。 - 修正步骤:
- 修改导入语句,将
import plotly.tools as tls替换为import chart_studio.tools as tls - 凭证设置的代码逻辑保持不变,参数(username、api_key)的用法完全一致
- 修改导入语句,将
修正后的完整代码:
import numpy as np import pandas as pd import cufflinks as cf import chart_studio.plotly as py # 替换为新版的工具模块导入 import chart_studio.tools as tls import plotly.graph_objs as go tls.set_credentials_file(username = "xxx", api_key = "yyyy")
额外说明:如果仅需在本地渲染图表、无需上传至Plotly云端平台,可以直接省略凭证设置的步骤,不影响本地绘图功能的使用。
内容的提问来源于stack exchange,提问作者Beck
相关产品推荐
相关产品推荐

