Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to plot data from JSON with matplotlib?

So I have some data in json format, here's a snippet:

"sell": [
           {
               "Rate": 0.001425,
               "Quantity": 537.27713514
           },
           {
               "Rate": 0.00142853,
               "Quantity": 6.59174681
           }
]

What's the easiest way to access Rate and Quantity so that I can plot it in Matplotlib? Do I have to flatten/normalize it, or create a for loop to generate an array, or can I use pandas or some other library to convert it into matplotlib friendly data automatically?

I know matplotlib can handle inputs in a few ways

plt.plot([1,2,3,4], [1,4,9,16])

plt.plot([1,1],[2,4],[3,9],[4,16])
like image 502
iontom Avatar asked Jun 18 '17 18:06

iontom


1 Answers

The simpliest is DataFrame constructor with DataFrame.plot:

import pandas as pd

d = {"sell": [
           {
               "Rate": 0.001425,
               "Quantity": 537.27713514
           },
           {
               "Rate": 0.00142853,
               "Quantity": 6.59174681
           }
]}

df = pd.DataFrame(d['sell'])
print (df)
     Quantity      Rate
0  537.277135  0.001425
1    6.591747  0.001429

df.plot(x='Quantity', y='Rate')

EDIT:

Also is possible use read_json for DataFrame.

like image 144
jezrael Avatar answered Sep 23 '22 23:09

jezrael