Python - How To Plot a Python Dictionary in Order of Key Values

ID : 201

viewed : 203

Tags : PythonPython Dictionary

vote vote

99

This tutorial explains how we can plot a dictionary in Python using the pyplot module of matplotlib library of Python. We will plot the dictionary in key-value pair, where x-axis of the plot will be the key of the dictionary and the y-axis will be the value of the dictionary.

Plot a Python Dictionary Using the pyplot Module of matplotlib Library

The code example below converts the dictionary into a list of key-value pairs, then sorts it using the sorted function so that our graph is ordered. After sorting, x and y values are extracted from the list using the zip function.

After getting the x and y axes’ values, we could pass them as arguments to the plt.plot function for graph plotting.

Example code:

import matplotlib.pylab as plt  my_dict = { 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1}  myList = my_dict.items() myList = sorted(myList)  x, y = zip(*myList)   plt.plot(x, y) plt.show() 

Output:

python plot dictionary

We can also add labels to the x-axis and y-axis and a title to the graph. The code example below shows how we can add them to the graph.

import matplotlib.pylab as plt  my_dict = { 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1}  myList = my_dict.items() myList = sorted(myList) x, y = zip(*myList)  plt.plot(x, y) plt.xlabel('Key') plt.ylabel('Value') plt.title('My Dictionary') plt.show() 

Output:

python plot dictionary with labels

  • Related HOW TO?