0

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')
2
  • Exactly which line is giving you an error? The error 'TypeError: 'str' object does not support item assignment' tends to arise when you try to modify a string object in place (change a character for example.) Strings are immutable, so you can't "change" one but you can make a changed copy. Commented Aug 24, 2016 at 4:50
  • @machine yearning: This line is giving me the TypeError: 'fig.append_trace(i, j, k)' Commented Aug 24, 2016 at 4:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I see. I will fix the x and make it an array. Thank you for the explanation. :)
Or rather, x is already an array. What you probably need to do is make sure each element of x is a go.Scatter object, instead of a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.