I am trying to create bar chart animation using plotly python and want to take it online

I am trying to create bar chart animation using plotly python and want to take it online

I am receiving below error:

Traceback (most recent call last):
File “plotly_charts.py”, line 989, in
inventoryAnimation()
File “plotly_charts.py”, line 976, in inventoryAnimation
plot_url = py.create_animations(fig, ‘invAnimation’, auto_open=False)
File “/usr/local/lib/python2.7/dist-packages/plotly-3.9.0-py2.7.egg/chart_studio/plotly/plotly.py”, line 2026, in create_animations
figure, grid = _extract_grid_from_fig_like(figure)
File “/usr/local/lib/python2.7/dist-packages/plotly-3.9.0-py2.7.egg/chart_studio/plotly/plotly.py”, line 1776, in _extract_grid_from_fig_like
trace_type = trace_dict.get(‘type’, ‘scatter’)
AttributeError: ‘Bar’ object has no attribute ‘get’

My code:

def inventoryAnimation():
    labels = ['Out in 30 days','Out in 15 days','Near, Out in 5 days','Past by 5 days','Past by 15 days','Past by 30 days']

    inv = pd.read_csv("temp_inv_animation.csv")
    dates = inv['date'].unique().tolist()
    parts = inv['mfg_part_id'].unique().tolist()
    list_of_lists = []
    i=0
    for p in parts:
        list_of_lists.append([])
        for l in labels:
            list_of_lists[i].append([])
        i+=1
    maxn, minn, count = 0.0, 0.0, 0
    for dt in dates:
        inv_for_date = inv[inv['date'] == dt]
        i=0
        for p in parts:
            j=0
            inv_for_date_part = inv_for_date[inv_for_date['mfg_part_id'] == p]
            for l in labels:
                if len(inv_for_date_part)==0:
                    x=0.0
                else:
                    inv_for_date_part_diff = inv_for_date_part[inv_for_date_part['diff'] == l]
                    if len(inv_for_date_part_diff) == 0:
                        x=0.0
                    else:
                        x=inv_for_date_part_diff['totalPrice'].sum()
                        if j>2:
                            x = -1*x
                if x < minn:
                    minn = x
                if x > maxn:
                    maxn = x
                #list_of_lists[part][label][dt]        
                list_of_lists[i][j].append(x)
                count+=1
                j+=1
            i+=1
    colour=['grey','lightgreen','green','yellow','orange','red']

    #make grid
    columns = []
    columns.append(Column(parts, 'y'))
    names = {}
    n=1
    for k in range(len(dates)):
        for j in range(len(labels)):
            data = []
            for i in range(len(parts)):
                data.append(list_of_lists[i][j][k])
            columns.append(Column(data, 'x'+str(n)))
            names[k*10+j] = 'x'+str(n)
            n+=1
    grid = Grid(columns)
    py.grid_ops.upload(grid, 'invAnimation_grid', auto_open=False)

    #make animation
    trace0 = []
    j=0
    for l in labels:
        ## Barplot
        trce=go.Bar(
            xsrc=grid.get_column_reference(names[j]),
            ysrc=grid.get_column_reference('y'),
            name=l,
            orientation='h',
            marker=dict(
                    color=colour[j],
                    line=dict(
                        color='rgb(8,48,107)',
                        width=1.5),
                )
        )
        trace0.append(trce)
    
    layout=dict(xaxis=dict(range=[minn, maxn], autorange=False, zeroline=False),
                yaxis=dict(zeroline=False, autorange=False),
                title='Inventory Animation for programId=PRG-199-21991-000', hovermode='closest',
                barmode='stack',
                updatemenus= [{'type': 'buttons',
                               'buttons': [{'label': 'Play',
                                            'method': 'animate',
                                            'args': [None]}]}])
    frames = []
    for k in range(1,len(list_of_lists[0][0])):
        frame = {'data': [], 'name': dates[k]}
        tracej = []
        for j in range(len(labels)):
            tracej.append(go.Bar(
                xsrc=grid.get_column_reference(names[k*10+j]),
                ysrc=grid.get_column_reference('y'),
                name=labels[j],
                orientation='h',
                marker=dict(
                    color=colour[j],
                    line=dict(
                        color='rgb(8,48,107)',
                        width=1.5),
                )
            ))
    
        frame['data'] = tracej
        frames.append(frame)
    
    data = trace0

    fig = dict(data=data, layout=layout, frames=frames)
    plot_url = py.create_animations(fig, 'invAnimation', auto_open=False)
    print plot_url

Kindly advise if bar chart animations are supported online by plotly python and if so what I am doing wrong?

Hi @gsudhanshu,

It looks like there’s a problem in create_animations when it is passed a figure that’s a dict that contains graph_objs objects. I just opened a bug report at https://github.com/plotly/plotly.py/issues/1616 to track it.

To work around the issue, replace

fig = dict(data=data, layout=layout, frames=frames)

with

fig = go.Figure(data=data, layout=layout, frames=frames)

Hope that helps,
-Jon

Thanks Jon, you are a life saver

Dear Jon,

Now I am facing the following error:

Traceback (most recent call last):
File “plotly_charts.py”, line 1110, in
inventoryAnimation()
File “plotly_charts.py”, line 1019, in inventoryAnimation
plot_url = py.create_animations(fig, ‘invAnimation’, auto_open=False)
File “/usr/local/lib/python2.7/dist-packages/chart_studio/plotly/plotly.py”, line 2043, in create_animations
file_info = _create_or_update(payload, ‘plot’)
File “/usr/local/lib/python2.7/dist-packages/chart_studio/plotly/plotly.py”, line 1468, in _create_or_update
res = api_module.create(data)
File “/usr/local/lib/python2.7/dist-packages/chart_studio/api/v2/plots.py”, line 18, in create
return request(‘post’, url, json=body)
File “/usr/local/lib/python2.7/dist-packages/retrying.py”, line 49, in wrapped_f
return Retrying(*dargs, **dkw).call(f, *args, **kw)
File “/usr/local/lib/python2.7/dist-packages/retrying.py”, line 206, in call
return attempt.get(self._wrap_exception)
File “/usr/local/lib/python2.7/dist-packages/retrying.py”, line 247, in get
six.reraise(self.value[0], self.value[1], self.value[2])
File “/usr/local/lib/python2.7/dist-packages/retrying.py”, line 200, in call
attempt = Attempt(fn(*args, **kwargs), attempt_number, False)
File “/usr/local/lib/python2.7/dist-packages/chart_studio/api/v2/utils.py”, line 172, in request
validate_response(response)
File “/usr/local/lib/python2.7/dist-packages/chart_studio/api/v2/utils.py”, line 82, in validate_response
raise exceptions.PlotlyRequestError(message, status_code, content)
chart_studio.exceptions.PlotlyRequestError: Sorry, a file named ‘invAnimation’ already exists

Kindly help

Thanks

Hi @gsudhanshu,

Hmm, I’m not able to reproduce this error, even if I run create_animations with the same filename repeatedly. What version of plotly.py are you using? Current version is 3.10, so if you’re not on that I’d recommend upgrading.

If you set the filename to a new name does it work? Or do you get the error even with a filename you’ve never used before?

-Jon

My plotly version is 3.10.0

This error occurs when there are more frames data for grid_upload()

for lower no. of frames say 15, it works

Thanks

Hi @gsudhanshu,

You’re probably running into the issue reported in https://github.com/plotly/plotly.py/issues/1622. This issue is for chart_studio.plotly.plot in a plotly.py v4 alpha release. The relationship is that the v3 implementation of create_animations is the basis for the v4 chart_studio.plotly.plot function. So in v4, the create_animations function won’t be necessary because chart_studio.plotly.plot will support figures with frames.

Feel free to try out the alpha, but otherwise I’m afraid you’ll need to either use unique file names or manually delete files in the Chart Studio interface before reusing file names.

-Jon