A simple verbose demo again, so that I don't forget. The script is just pasted here until the python format and copying with IE11 is fixed. The script is pretty self explanatory and no effort has been made to simplify it. Cross-posted at
https://geonet.esri.com/blogs/dan_patterson/2014/08/18/collections-in-numpy-producing-frequency-distributions-and-graphing
'''
CollectionsDemo.py
Author: Dan.Patterson@carleton.ca
Purpose:
To demonstrate the utility of using the collections module to
obtain a simple frequency distribution, in this case, a list
of random integers. It is written verbosely so that the user
can see the sequence of events and the results of the various
methods.
A sequence of random numbers is generated and a dictionary of
key:values is produced by collections.Counter. The resultant
keys are cloned to "classes" to prevent alteration of the
initial keys. An extra class is appended to the list to ensure
that the last class in the keys is included since the behaviour
of histogram is to combine the last two classes into
one frequency (long story). I just add a value of 1 to the last
class to produce an extra bin.
A histogram is produced which contains the classes and the frequency
for those classes.
'''
import collections
import random
import numpy as np
from matplotlib import pyplot as plt
rand_int = [random.randrange(1,6) for i in xrange(0,25)]
dict = collections.Counter(rand_int)
keys = dict.keys()
counts = dict.values()
classes = keys[:] #clone the keys
classes.append(classes[-1] + 1) #to ensure that the last bin has values
histo = np.histogram(rand_int,classes)
plt.hist(rand_int,bins=classes,align='left')
plt.title("Sample Histogram", loc='center')
plt.xlabel("class"); plt.ylabel("frequency")
plt.show()
print "\nCollections and pylab\n"
print "Random integers:\n", rand_int
print "Collections dict: ", dict
print " keys: ", keys
print " values (freq): ", counts
print "histogram ", histo
print " classes: ", histo[1]
print " frequency: ", histo[0]
No comments:
Post a Comment