Plotly.py: JSON output type

Created on 14 Jan 2017  路  8Comments  路  Source: plotly/plotly.py

Would it be possible to add a JSON output type to plotly.offline.plot which could generate just a JSON string for data and layout without the div and script tags? I'd like to be able to generate my plots in python and just send a plot to a browser over a websocket.

enhancement

Most helpful comment

I'm currently using

serialized = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

d = json.loads(serialized)
loaded_fig = go.Figure(data=d['data'], layout=d['layout'])

All 8 comments

@syamajala have you tried using: https://docs.python.org/2/library/json.html ?

import plotly.graph_objs as go
import json

month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
high_2014 = [28.8, 28.5, 37.0, 56.8, 69.7, 79.7, 78.5, 77.8, 74.1, 62.6, 45.3, 39.9]
low_2014 = [12.7, 14.3, 18.6, 35.5, 49.9, 58.0, 60.0, 58.6, 51.7, 45.2, 32.2, 29.1]

trace0 = go.Scatter(
    x = month,
    y = high_2014,
    name = 'High 2014'
)
trace1 = go.Scatter(
    x = month,
    y = low_2014,
    name = 'Low 2014',
)
data = [trace0, trace1]

# Edit the layout
layout = dict(title = 'Average High and Low Temperatures in New York')

fig = dict(data=data, layout=layout)
str_json = json.dumps(fig)
str_json

Thats what I ended up doing, but I found I have to call json.dumps with plotly.utils.JSONEncoder as the cls argument. I think it might be because I was using numpy arrays. It would be nice if plotly.offline.plot just had a json output type so i wouldn't have to do this stuff myself. I could just call plot(output_type='json') and get a string back.

It's unlikely that we will add this option but community PRs are welcome.

I've made the modifications. Do I have to run unit tests with both nose and tox? Or is nose by itself enough?

EDIT: I created a pull request.

Any hope for this issue or PR https://github.com/plotly/plotly.py/pull/704? I have a similar use case, but this issue looks forgotten.

I'm currently using

serialized = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

d = json.loads(serialized)
loaded_fig = go.Figure(data=d['data'], layout=d['layout'])

This functionality will be added with the to_json and write_json functions in the plotly.io module. See https://github.com/plotly/plotly.py/pull/1188 for progress

Was this page helpful?
0 / 5 - 0 ratings