首页 > 解决方案 > Plotly 子图:IndexError:元组索引超出范围

问题描述

我正在尝试运行 Plotly 教程以在(https://plot.ly/python/creating-and-updating-figures/)上制作子图:

from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=1)
fig.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"), row=1, col=1)
fig.add_trace(go.Bar(y=[2, 1, 3]), row=2, col=1)
fig.show()

我收到以下错误:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
 in 
      1 from plotly.subplots import make_subplots
      2 fig = make_subplots(rows=2, cols=1)
----> 3 fig.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"), row=1, col=1)
      4 fig.add_trace(go.Bar(y=[2, 1, 3]), row=2, col=1)
      5 fig.show()

~\AppData\Local\Continuum\anaconda3\envs\quantlib\lib\site-packages\plotly\basedatatypes.py in add_trace(self, trace, row, col)
   1070         # ----------------
   1071         for key_path_str, v in restyle_data.items():
-> 1072 
   1073             # Track whether any of the new values are cause a change in
   1074             # self._data

~\AppData\Local\Continuum\anaconda3\envs\quantlib\lib\site-packages\plotly\basedatatypes.py in add_traces(self, data, rows, cols)
   1153         # In batch mode
   1154         # -------------
-> 1155         # Add key_path_str/val to saved batch edits
   1156         else:
   1157             if trace_index not in self._batch_trace_edits:

~\AppData\Local\Continuum\anaconda3\envs\quantlib\lib\site-packages\plotly\basedatatypes.py in _set_trace_grid_position(self, trace, row, col)
   1254 
   1255     @staticmethod
-> 1256     def _set_in(d, key_path_str, v):
   1257         """
   1258         Set a value in a nested dict using a key path string

IndexError: tuple index out of range

任何想法如何纠正?先感谢您。

标签: pythonpython-3.xplotly

解决方案


只需将listas 传递给tuple

from plotly.subplots import make_subplots
### specify it next time
import plotly.graph_objects as go

fig = make_subplots(rows=2, cols=1)
fig.add_trace(go.Scatter(y=tuple([4, 2, 1]), mode="lines"), row=1, col=1)
fig.add_trace(go.Bar(y=tuple([2, 1, 3])), row=2, col=1)
fig.show()

结果: 在此处输入图像描述


推荐阅读