MatPlotLib Tutorial 1
--D. Thiebaut 10:27, 25 April 2011 (EDT)
|
Other Sources of Information
- MatPlotLib's tutorials, at http://matplotlib.sourceforge.net/users/pyplot_tutorial.html
Setup
We use the Eclipse IDE and PyDev to develop Python packages. If you want to setup your environment to match the one used here you will need to install:
- Eclipse: http://www.eclipse.org/downloads/
- Python: http://www.python.org/download/
- PyDev: http://pydev.org/download.html
- EDP from Enthought: https://www.enthought.com/products/. It contains all you need to run MatPlotLib.
Default Python
- You should make the Python version installed by EDP as the default Python interpreter for Eclipse/PyDev.
- First open a Terminal window and type:
which python /Library/Frameworks/Python.framework/Versions/Current/bin/python
- Record the answer to the command and enter it in Eclipse's Preference window for PyDev:
Testing
- To test that your installation is ready to go, load up the code from this URL http://matplotlib.sourceforge.net/examples/api/unicode_minus.html and run it. You should get a plot, as shown below:
Scatter Plot of (X, Y) points
The Simplest Approach
- You have an array of N Y-values, and you want to display them at X-values ranging from 0 to N-1:
def plot2():
plt.plot([1,3,2,4])
plt.ylabel('Intensity')
plt.show()
Changing Colors and Adding Markers
def plot3():
plt.plot([1,3,2,4], 'ro-' )
plt.ylabel('Intensity')
plt.show()
To change the color, simply use a string at the last parameter of the plot() function and define the color, 'r' for red, for example, and the type of marker, 'o' for circle. 'ro' would display red circles only. 'ro-' would display red circles linked by a line. This is similar to the Matlab syntax. '--rs' would display a dash line between red squares. ':bs' would display a dotted line between blue squares.
Two list of coordinates
def plot4():
x = [1, 2, 3, 4, 5, 6]
y = [1, 2, 4, 3, 6, 5]
plt.plot( x, y, ':rs' )
plt.axis( [0, 10, 0, 6])
plt.xlabel( "X values" )
plt.ylabel( "Y values" )
plt.show()
Here we present the plot with two arrays, one for the X values, one for the Y values. We also define the range of values for the X-axis and the range of values for the Y-axis, and provide labels for each one.