Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Visualising JSON data using python libraries

I am visualising the json data using mathplotlib and pandas

  {
    "data_point": 0,
    "Add": 2977780,
    "Add_num": 38595
  },
  {
    "data_point": 1,
    "Add": 2809086,
    "Add_num": 36534
  },
  {
    "data_point": 2,
    "Add": 2825428,
    "Add_num": 36534
  },
  {
    "data_point": 3,
    "Add": 2826861,
    "Add_num": 36564
  }]

This is the data now i want to draw a graph with y-axis as value obtained from division of "Add" and "Add_num" (Add/Add_num) and "data_point" as x-axis. Is there a way to do this in python code or I need to process json data to add Add_avg field in json file(i.e. Add_avg = Add/Add_num)

Code to draw the graph

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import json
import pandas as pd

a_file = open("./data.json", "r")
json_object = json.load(a_file)
a_file.close()
df = pd.DataFrame(json_object)
df.plot(x='data_point', y='Add',color='maroon', marker='o')
df.plot(x='data_point', y='Add_num',color='maroon', marker='o')

>Solution :

You can use matplotlib directly to plot, then you can do the calculations while plotting. Or you can indeed add another column:

import json
import pandas as pd
from matplotlib import pyplot as plt

js = """[ {
    "data_point": 0,
    "Add": 2977780,
    "Add_num": 38595
  },
  {
    "data_point": 1,
    "Add": 2809086,
    "Add_num": 36534
  },
  {
    "data_point": 2,
    "Add": 2825428,
    "Add_num": 36534
  },
  {
    "data_point": 3,
    "Add": 2826861,
    "Add_num": 36564
  }]"""

# Use loads instead of load since in my case the json is a string:
df = pd.DataFrame(json.loads(js))

# plot:
fig, ax = plt.subplots(1)
ax.plot(df['data_point'], df['Add']/df['Add_num'])
plt.show()

Or add a new column:

df['Add_avg'] = df['Add']  / df['Add_num']
df.plot(x='data_point', y='Add_avg', color='maroon', marker='o')
plt.show()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading