Problem adding in trace to Plotly figure that was converted from Matplotlib

Viewed 2615

I am trying to add in a new scatter trace based on the instructions on this web page: https://plot.ly/matplotlib/modifying-a-matplotlib-figure/

However, when I try to run the following code:

plotly_fig['data'].append( dict(x=x, y=logx, type='scatter', mode='lines') )

I receive the following error:

plotly_fig['data'].append( dict(x=x, y=logx, type='scatter', mode='lines') ) AttributeError: 'tuple' object has no attribute 'append'

So far I have tried:

1.) plotly_fig.update(data=dict(x=x, y=logx, type='scatter', mode='lines'))

which doesn't seem to do anything.

2.) plotly_fig.add_scatter(name= "test", mode='lines', xaxis='x', yaxis='y',x=x.tolist(), y=sinx.tolist(), line= {'color': 'rgba (31, 119, 180, 1)', 'dash': 'solid', 'width': 1.5})

which seems to add in the trace but when I run:

py.plot(plotly_fig, filename='test.html')

the new trace doesn't plot.

3.) new_trace = dict(type='scatter', x=x, y=sinx, mode='lines', line= {'color': 'rgba (31, 119, 180, 1)', 'dash': 'solid', 'width': 1.5})

plotly_fig.append_trace(new_trace, 0, 0)

which returns the error: "In order to reference traces by row and column, you must first use plotly.tools.make_subplots to create the figure with a subplot grid."

Here is my full code with both of the methods mentioned above, commented out.

import pprint
import matplotlib.pyplot as plt
import plotly.offline as py
import plotly.tools as tls
import plotly.graph_objs as go

x =  np.linspace(np.pi, 3*np.pi, 1000)
sinx = np.sin(x)
logx = np.log(x)


fig, ax = plt.subplots(figsize=(5,6))
ax.plot(x, logx)
ax.set_title('Two Curves')


plotly_fig = tls.mpl_to_plotly(fig)`
pp = pprint.PrettyPrinter(indent=4)`
pp.pprint(plotly_fig)`

plotly_fig['data'].append( dict(x=x, y=logx, type='scatter', mode='lines') )

#plotly_fig.update(data=dict(x=x, y=logx, type='scatter', mode='lines'))

#plotly_fig.add_scatter(name= "test", mode='lines', xaxis='x', yaxis='y',x=x.tolist(), y=sinx.tolist(), line= {'color': 'rgba (31, 119, 180, 1)', 'dash': 'solid', 'width': 1.5})

#new_trace = dict(type='scatter', x=x, y=sinx, mode='lines', line= {'color': 'rgba (31, 119, 180, 1)', 'dash': 'solid', 'width': 1.5})
    #plotly_fig.append_trace(new_trace, 0, 0)

pp.pprint(plotly_fig)

py.plot(plotly_fig, filename='test.html')
1 Answers

It looks like the example code you’re using has become deprecated since plotly 3.0 has switched to representing Figure data as a tuple instead of a list. Because tuples are immutable, you received the error you described.

See docs: https://github.com/plotly/plotly.py/blob/master/migration-guide.md#migration-to-version-3

So, change the line

plotly_fig['data'].append( dict(x=x, y=logx, type='scatter', mode='lines') )

to:

plotly_fig.add_trace(dict(x=x, y=logx, type='scatter', mode='lines'))
Related