Thursday, July 15, 2010

matplotlib basics


Simple Plot
import
matplotlib.pyplot as plt
plt.plot([1,2,3,4])
# plot a set of points (1,1) and (3,2)
plt.plot([1,3],[1,2],'ro')
# Or plot as a bunch of connect line segments
plt.plot([2,4,6],[2,4,6])
# set a label for the x and y axis
plt.ylabel('some numbers')
plt.xlabel('joe rocks')
# set the axis [xmin, xmax, ymin, ymax ]
plt.axis([0,6,0,5])
# 'show' the graph

plt.show()


Plot a function
As far as I can tell matplotlib cannot plot a continuous function.
Instead, create a range of distinct numbers:

import numpy as np
import matplotlib.pyplot as plt
# create a range of numbers from 0 to 5. increment by .1
x = np.arange(0.,5.,.1)
# apply a function to that
y = np.sin(x)
# plot with extra display params
plt.plot(x,y,linewidth=2.0, label='joeplot', color='blue')
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.axis([0,5,-1,1])
plt.grid(True)
plt.show()

Make a cool heatmap
import numpy as np
import matplotlib.pyplot as plt
#x = y = np.linspace(-5, 5, 12)
# create a grid of 12 X coordinates and 12 Y coordinates
# these coordinates will be used to represent specific locations on
# the grid. the meshgrid() basically creates a nice uniform coordinate grid
X,Y = np.meshgrid([1,2,3,4],[1,2,3])
# X,Y = np.meshgrid(x, y)
# these ravel functions basically make the 2d arrays created above into lists
x = X.ravel()
y = Y.ravel()
plt.subplot(111)
plt.hexbin(x,y,C=[1,2,3,3,2,2,3,3,2,3,3,4], gridsize=30)
cb = plt.colorbar()
cb.set_label('Heat Value')
plt.axis([x.min(), x.max(), y.min(), y.max()])
plt.grid(True)


http://stackoverflow.com/questions/2369492/generate-a-heatmap-in-matplotlib-using-a-scatter-data-set

No comments: