Fxs7576 Fxs7576 - 3 months ago 46
Python Question

For Loop on Plotly Python

I am trying to replace

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


with the for loop code

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)


so that it will be more scalable as I add more figures. However, the loop code keeps returning 'TypeError: 'str' object does not support item assignment'. What did I do wrong?

Here is the code similar with the one from 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')

Answer

In this code it looks like trace1 is some kind of array-like data structure:

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

So I imagine that when you call fig.append_trace(trace1, 1, 1) it's adding an element to this array-like structure, the first parameter.

However in your reimplementation, you've turned the trace data into a string:

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)

Here i is an element of x which is in turn a string like 'trace%s'%(item + 1). But you cannot append an element to a string. Python strings are immutable. So when you call append_trace you naturally get an error here about not being able to do what you want with strings.

Comments