Home > Net >  seaborn plot in json format for front end
seaborn plot in json format for front end

Time:12-27

I created a dummy plot by:

import seaborn as sns
x=[10 ,20,30 ,40,50]
y=[100,30,200,150,80]
sns.barplot(x,y);

enter image description here

this is just an example.

I am generating different graphs in seaborn, matplotlib, etc.

now the front end guy want the generated graph-images in json format, for customization

what should I do.

CodePudding user response:

j_1=dict(zip(x,y))
j_2=dict(zip(y,x))

You have both the options in json now.

# j_1 is {10: 100, 20: 30, 30: 200, 40: 150, 50: 80}

Or

# j_2 is {100: 10, 30: 20, 200: 30, 150: 40, 80: 50}

If you want to print in Json format:

import json 
json_object_1 = json.dumps(j_1, indent = 2)

#
{
  "10": 100,
  "20": 30,
  "30": 200,
  "40": 150,
  "50": 80
}

CodePudding user response:

JSON is a text format. There are two main options:

  • Good one - send the raw values to frontend and use a plotting library to visualize it client-side.
  • Okay one - render plot on the server and send image to frontend. SSR example with Flask.

Client-side rendering allows for making interactive plots with zoom, highlights and whatnot. The result would be dynamic, and users like that. Examples of those libraries include D3.js, Plotly, Highcharts, Google Charts, and many more.

The approach would ideally depend on your use case. If you provide charts as parts of static content (think monthly blog posts reporting data), backend rendering and displaying plots as images would be okay. If your service focuses on continuously delivering data, frontend guy should really pick up the slack there.

Anyroad, a variant on the server-side rendering is encoding the produced image in base64 and appending to the JSON response. I am not convinced it makes sense to not just fetch the image as file (mimetype="image/png") instead, but this is what matplotlib documentation also suggests doing:

buf = BytesIO()
fig.savefig(buf, format="png")
data = base64.b64encode(buf.getbuffer()).decode("ascii")

You can then return the encoded string with base64 representation (modern versions of Flask jsonify the response and add appropriate headers and status automagically):

return {"plot": f"data:image/png;base64,{data}", **dict_with_other_response_data}
  • Related