Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python plot with matplotlib a json file data

I have the following json file and I would like to make bar graphs based on bytes and timestamp. Noticed timestamps provided on the file are not in order, and they need to .

{
    "success":true,
        "data":[
            {

                "record_id":258585618,
                "timestamp":"2018-01-21 22:34:34",
                "bytes":29466,

            }
            ,
            {
                "record_id":258585604,
                "timestamp":"2018-01-21 22:33:14",
                "bytes":37892,
            }
            ,
            {
                "record_id":258584399,
                "timestamp":"2018-01-21 22:37:40",
                "bytes":36396,
            }
        ]
    }

Thank you very much!!!

like image 322
sundark Avatar asked Nov 15 '25 18:11

sundark


1 Answers

Edit: I have now sorted the dates for the bar graph.

You could do something like this:

import json
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
data = json.dumps({
    "success":True,
        "data":[
            {

                "record_id":258585618,
                "timestamp":"2018-01-21 22:34:34",
                "bytes":29466,

            }
            ,
            {
                "record_id":258585604,
                "timestamp":"2018-01-21 22:33:14",
                "bytes":37892,
            }
            ,
            {
                "record_id":258584399,
                "timestamp":"2018-01-21 22:37:40",
                "bytes":36396,
            }
        ]
    })

data = json.loads(data)
dates = [i['timestamp'] for i in data["data"]]
values = [i['bytes'] for i in data['data']]

df = pd.DataFrame({'dates':dates, 'values':values})
df['dates']  = [pd.to_datetime(i) for i in df['dates']]

print(df.sort_values(by='dates'))

                dates  values
1 2018-01-21 22:33:14   37892
0 2018-01-21 22:34:34   29466
2 2018-01-21 22:37:40   36396

plt.bar(dates, values)

enter image description here

like image 90
briancaffey Avatar answered Nov 17 '25 08:11

briancaffey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!