Quick start to matplotlib


Sometimes we just want to use a library without going into details and things that doesn't really matter to us. So after I spent sometime yesterday I figured that it would be nice to create a simple examples of how to use matplotlib (just the simple stuff).

Assuming you know python and have matplotlib already installed (google anaconda for more info).

In the below example I'm using sklearn library to do some machine learning but it is not required.

from sklearn.cluster import KMeans

import matplotlib.pyplot as plt
from matplotlib import colors as matplot_colors
import six

colors = list(six.iteritems(matplot_colors.cnames))

#assuming your data is something like this
data = [[1,1], [2,2], [3,3]]
num_of_clusters = len(data)
model = KMeans(n_clusters=num_of_clusters)
print len(data)
print len(data[0])
model.fit(data)

for idx, bbb in enumerate(data):
    bus_station_point, time_point = bbb
    for clus in range(num_of_clusters):
        if model.labels_[idx] == clus:
            cc = colors[clus]
            plt.scatter([time_point],[bus_station_point], c=cc) # draw points
for clus in range(num_of_clusters):
    y, x = model.cluster_centers_[clus]
    plt.scatter([x], [y], c=colors[clus], marker="x", s=80) # draw x
for bus, time_string in data:#show numbers
    plt.annotate(bus, (time_string, bus))
for idx, xy in enumerate(data[:-1]):#lines
    plt.plot([data[idx][1], data[idx+1][1]], [data[idx][0], data[idx+1][0]])
plt.show()






References:
http://www.galvanize.com/blog/introduction-k-means-cluster-analysis/#.V9cva5N94o8
http://matplotlib.org/examples/shapes_and_collections/scatter_demo.html
http://matplotlib.org/1.2.1/examples/pylab_examples/scatter_demo.html
http://matplotlib.org/examples/pylab_examples/scatter_star_poly.html
http://matplotlib.org/examples/color/named_colors.html
http://stackoverflow.com/questions/14432557/matplotlib-scatter-plot-with-different-text-at-each-data-point
http://stackoverflow.com/questions/6834483/how-do-you-create-line-segments-between-two-points

Comments

Popular Posts