Sunday, 9 August 2015

Visual Representation using Charts

In this blogpost we will try understanding how the function, Charts, works. Following is the example of a Barplot 

 Taking the Radish Survey we can create a chart in the following manner.  


Let us try and understand the code. One Step at a time

import matplotlib.pyplot as plt import numpy as np names = [] votes = [] for radish in counts: names.append(radish) votes.append(counts[radish]) x = np.arange(len(counts)) plt.bar(x, votes) plt.xticks(x + 0.5, names, rotation=90)


First, Two modules are being imported here. Pyplot is a way to plot graph data with Matplotlib. NumPy provides number functions for Python.

names = [] votes = [] for radish in counts: names.append(radish) votes.append(counts[radish])

Now, This loop does the formatting of the dictionary so that it can be easily sent to matplotlib.

x = np.arange(len(counts))

This solves the purpose of spreading the numbers evenly on the X-axis.

plt.bar(x, votes)

This function creates the actual bargraph where x is the position and votes are the height.

plt.xticks(x + 0.5, names, rotation=90)

This specifies a range of values to use as labels.




No comments:

Post a Comment