In this blog we will try to focus on creating bar chart for our "Voting" assignment.
We will be using matplotlib because matplotlib tries to make easy things easy and hard things possible. You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc, with just a few lines of code.
Let us tr a small example before drawing a char for our voting problem. Please refer to the below code snippet.
pyplot is one way to plot graph data with MatPlotlib. Provides a MATLAB-like plotting framework.pylab combines pyplot with numpy into a single namespace. This is convenient for interactive work, but for programming it is recommended that the namespaces be kept separate.
If you want to use matplotlib directly from Python instead of via IPython Notebook, you just need to add one final line to each of your programs:
plt.show(). This will display a window with the chart you created, and pause the script until you close it.
The graph to the right is the output of above code. Now let us try to draw a bar chart for our voting example.
Please refer below code snippet to draw the bar chart to count number of votes of each category of radish.
Adding comments has made our task easy.We're importing two modules - pyplot is one way to plot graph data with Matplotlib. It's modelled on the way charting works in another popular commercial program, MATLab.NumPy is a module providing lots of numeric functions for Python. This loop processes the dictionary into a format that's easy to send to matplotlib - a list of radish names (for the labels on the bars) and a list of vote counts (for the actual graph.)
We create a range of indexes for the X values in the graph, one entry for each entry in the "counts" dictionary, numbered 0,1,2,3,etc. This will spread out the graph bars evenly across the X axis on the plot.
np.arrange : is a NumPy function like the range() function in Python, only the result it produces is a "NumPy array".
plt.bar() : creates a bar graph, using the "x" values as the X axis positions and the values in the votes array (ie the vote counts) as the height of each bar.
plt.xticks() : specifies a range of values to use as labels ("ticks") for the X axis.
To summarize, we have created bar chart using Matplot library. We will see different charts in Python in upcoming blogs.
Thanks for the post. Helps in understanding it step by step.
ReplyDeletenice one!!!
ReplyDelete