簡體   English   中英

在Plotly Python上循環

[英]For Loop on Plotly Python

我正在嘗試更換

fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 2, 1)

與for循環代碼

totalPlot = 2
x = ['trace%s'%(item + 1) for item in range(totalPlot)]
y = [(item + 1) for item in range(totalPlot)]
z = totalPlot * [1]

for i, j, k in zip(x, y, z):
    fig.append_trace(i, j, k)

這樣,當我添加更多數字時,它將具有更大的可擴展性。 但是,循環代碼不斷返回“ TypeError:'str'對象不支持項目分配”。 我做錯了什么?

這是與Plotly相似的代碼:

from plotly import tools
import plotly.plotly as py
import plotly.graph_objs as go

trace1 = go.Scatter(
    x=[1, 2, 3],
    y=[4, 5, 6]
)
trace2 = go.Scatter(
    x=[20, 30, 40],
    y=[50, 60, 70],
)

fig = tools.make_subplots(rows=2, cols=1)


# ----- Loop here ------- START
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 2, 1)
# ----- Loop here ------- END

fig['layout'].update(height=600, width=600, title='i <3 subplots')
py.iplot(fig, filename='make-subplots')

在這段代碼中, trace1看起來是某種類似於數組的數據結構:

trace1 = go.Scatter(
    x=[1, 2, 3],
    y=[4, 5, 6]
)

所以我想像一下,當您調用fig.append_trace(trace1, 1, 1)它會在此類似數組的結構中添加一個元素,第一個參數。

但是,在重新實現中,您已將跟蹤數據轉換為字符串:

x = ['trace%s'%(item + 1) for item in range(totalPlot)]
...
for i, j, k in zip(x, y, z):
    fig.append_trace(i, j, k)

在這里, ix的元素,它又是一個字符串,例如'trace%s'%(item + 1) 但是您不能將元素附加到字符串。 Python字符串是不可變的。 因此,當您調用append_trace您自然會在此處收到有關無法使用字符串執行所需操作的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM