Matplotlib - plotting a dictionary using matplot lib



 # Dictionary - Histograms and matplotlib


# Create a histogram based on the frequency of characters in given string


# Histogram - String - Word Frequency


import matplotlib.pyplot as plt


import operator


string1 = "An algorithm is a step-by-step procedure to solve a given problem. It is a well-defined computational procedure that takes some values as input, manipulates them using a set of instructions and produces some values as output and terminates in a finite amount of time. An algorithm, when formally written in a programming language is called a program, or code. Derivation of an algorithm that solves the problem and conversion of the algorithm into code, together,  is known as Algorithmic Problem Solving."



string1 = string1.lower()


ch = set(string1)


D = {c:string1.count(c) for c in ch if c.isalpha()}  


print("Histogram")

print("Length of dictionary = ", len(D))

print(D)


plt.bar(range(len(D)), list(D.values()), align='center')

plt.xticks(range(len(D)), list(D.keys()))


plt.xlabel('Character')

plt.ylabel('Frequency')

plt.title('Character Frequency in given string.')


plt.show()


"""

Output

>python matplot.py

Histogram

Length of dictionary =  22

{'k': 2, 'e': 40, 'n': 30, 'g': 14, 's': 26, 'u': 14, 'o': 38, 'i': 32, 't': 37, 'r': 25, 'l': 22, 'b': 4, 'w': 4, 'f': 7, 'p': 14, 'v': 8, 'a': 39, 'y': 2, 'm': 20, 'd': 12, 'c': 10, 'h': 12}


"""

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu