Plot data from JSON file using matplotlib in Python
Welcome to the tutorial on plotting data from JSON file using matplotlib in Python.
Firstly, you should know how to create a JSON file.
Creating a JSON file
Name the file as ___.json, in our case we have named the file 01.json.
Write the following code in that file.
INPUT:
{"jan":1,"feb":2,"mar":3,"apr":7,"may":8,"jun":5,"jul":7,"aug":5,"sep":3,"oct":1,"nov":2,"dec":1}
Now, we will plot this data using matplotlib in python.
Plotting data using matplotlib
INPUT:
We have loaded the data using json.load(open(‘file-name’, ‘r’)) in the readable format.
#1 import json import matplotlib.pyplot as plt #2 data_1=json.load(open('01.json','r')) #3 axis_x=[i for i in data_1] axis_y=[data_1[i] for i in data_1]
In this, axis_x is a list containing all month names and axis_y is a list containing no. of monthly entries.
Here, we have set :
- keys from the dictionary data loaded from JSON file i.e month names as x-axis and
- values i.e entries during a month as y-axis.
OUTPUT:
Further, include the following in the previous code:
INPUT:
#4 plt.bar(axis_x,axis_y) plt.xlabel("Month") plt.ylabel("Entries") plt.title("Monthly Entries") plt.show()
Here, we have plotted a bar graph showing entries in a month.
OUTPUT:
Leave a Reply