Matplotlib: Difference between revisions
imported>Jesstess |
imported>Jesstess |
||
Line 15: | Line 15: | ||
=== 1. Install the project dependencies === |
=== 1. Install the project dependencies === |
||
Installing matplotlib |
Installing matplotlib is unfortunately rather complicated on OSX and Windows. Please ask for help if you get stuck or don't know where to start! |
||
First, install <code>numpy</code>. On Linux, you can use your package manager to install the <code>python-numpy</code> package. On Windows and OSX, you can download the appropriate binary from http://sourceforge.net/projects/numpy/files/NumPy/1.7.1/. |
|||
==== Windows users only ==== |
|||
Then, install <code>matplotlib</code>. On Linux, you can use your package manager to install the <code>python-matplotlib</code> package. On Windows and OSX, you can download the appropriate binary from https://github.com/matplotlib/matplotlib/downloads/. |
|||
# Download and install numpy from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy |
|||
# Download and install matplotlib from http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib |
|||
If either of these installs fails, fear not! Wave over a staff member and we'll help. |
|||
==== Mac OS X users only ==== |
|||
Getting matplotlib installed on OS X is unfortunately convoluted. Please wave over a staff member and we'll help you through the installation process that makes the most sense for your computing environment. |
|||
<b>Option 1: install binaries</b><br/> |
|||
# Follow the instructions at http://penandpants.com/2012/03/01/install-python-2/, which will walk you through installing a new Python, NumPy, SciPy, and finally matplotlib. |
|||
* Pros: you don't have to compile from source. |
|||
* Cons: you have to install a new Python, which could possibly interact negatively with existing libraries. |
|||
<b>Option 2: install from source</b> |
|||
# If you do not already have a C compiler installed, you'll need to install one before you install matplotlib. You have several options depending on your situation (ask a staff member for help picking one): |
|||
#* Download and install Xcode (1.5 GB) from https://developer.apple.com/xcode/ |
|||
#* Download and install Command Line Tools for Xcode (175 MB) from https://developer.apple.com/downloads/index.action. This requires an Apple Developer account (free, but you have to sign up). |
|||
#* Download and install kennethreitz's gcc installer (requires OS X 10.6 or 10.7) from https://github.com/kennethreitz/osx-gcc-installer/ |
|||
# Unpack the latest matplotlib tarball from http://sourceforge.net/projects/matplotlib/files/matplotlib/ |
|||
# Follow the instructions in <code>README.osx</code> |
|||
* Pros: you get to use your existing Python installation. |
|||
* Cons: you have to install a C compiler and compile from source. |
|||
<!-- |
|||
# Download and install numpy from http://sourceforge.net/projects/numpy/ |
|||
# Read http://matplotlib.sourceforge.net/faq/installing_faq.html#install-osx-binaries and then download and install matplotlib from http://sourceforge.net/projects/matplotlib/files/matplotlib/ |
|||
--> |
|||
==== Linux users only ==== |
|||
# Install the <code>python-numpy</code> package through your package manager |
|||
# Install the <code>python-matplotlib</code> package through your package manager |
|||
=== 2. Download and un-archive the Matplotlib project skeleton code === |
=== 2. Download and un-archive the Matplotlib project skeleton code === |
Revision as of 00:44, 25 May 2013
Project
Learn how to plot data with the matplotlib plotting library. Ditch Excel forever!
Goals
- practice reading data from a file
- practice using the matplotlib Python plotting library to analyze data and generate graphs
Project setup
1. Install the project dependencies
Installing matplotlib is unfortunately rather complicated on OSX and Windows. Please ask for help if you get stuck or don't know where to start!
First, install numpy
. On Linux, you can use your package manager to install the python-numpy
package. On Windows and OSX, you can download the appropriate binary from http://sourceforge.net/projects/numpy/files/NumPy/1.7.1/.
Then, install matplotlib
. On Linux, you can use your package manager to install the python-matplotlib
package. On Windows and OSX, you can download the appropriate binary from https://github.com/matplotlib/matplotlib/downloads/.
If either of these installs fails, fear not! Wave over a staff member and we'll help.
2. Download and un-archive the Matplotlib project skeleton code
Un-archiving will produce a Matplotlib
folder containing several Python and text files.
3. Test your setup
Run the basic_plot.py
script in your Matplotlib
directory. A window with a graph should pop up.
Project steps
1. Create a basic plot
-
Run
python basic_plot.py
. This will pop up a window with a dot plot of some data. -
Open
basic_plot.py
. Read through the code in this file. The meat of the file is in one line:pyplot.plot([0, 2, 4, 8, 16, 32], "o")
In this example, the first argument to
pyplot.plot
is the list of y values, and the second argument describes how to plot the data. If two lists had been supplied,pyplot.plot
would consider the first list to be the x values and the second list to be the y values. - Change the plot to display lines between the data points by changing
pyplot.plot([0, 2, 4, 8, 16, 32], "o")
to
pyplot.plot([0, 2, 4, 8, 16, 32], "o-")
-
Add x-values to the data by changing
pyplot.plot([0, 2, 4, 8, 16, 32], "o-")
to
x_values = [0, 4, 7, 20, 22, 25] y_values = [0, 2, 4, 8, 16, 32] pyplot.plot(x_values, y_values, "o-")
Note how matplotlib automatically resizes the graph to fit all of the points in the figure for you.
-
Read about how to generate random integers on http://docs.python.org/library/random.html#random.randint.
Then, instead of hard-coding y values in
basic_plot.py
, generate a list of random y values and plot them. An example plot using random y values might look like this:
Read these short documents:
- Pyplot tutorial (just this one section; stop before the next section "Controlling line properties"): http://matplotlib.sourceforge.net/users/pyplot_tutorial.html#pyplot-tutorial
- List of line options, including line style and marker shapes and colors: http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot
Check your understanding:
- What does matplotlib pick as the x values if you don't supply them yourself?
- What options would you pass to
pyplot.plot
to generate a plot with red triangles and dotted lines?
2. Plotting the world population over time
-
Run
python world_population.py
. This will pop up a window with a dot plot of the world population over the last 10,000 years. -
Open
world_population.py
. Read through the code in this file. In this example, we read our data from a file. Open the data fileworld_population.txt
and examine the format of the file. - Find the documentation on http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot for customizing the linewidth of plots. Then change the world population plot to use a magenta, down-triangle marker and a linewidth of 2.
World population resources:
- File input and output: http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files.
- Splitting sprints into parts based on a delimiter: http://www.hacksparrow.com/python-split-string-method-and-examples.html
Check your understanding:
- In
world_population.py
, what doesfile("world_population.txt", "r").readlines()
return? - In
world_population.py
, what doespoint.split()
return?
3. Plotting life expectancy over time
In a new file, write code to plot the data in life_expectancies_usa.txt
. The format in this file is <year>,<male life expectancy>,<female life expectancy>.
You can call pyplot.plot
multiple times to draw multiple lines on the same figure. For example:
pyplot.plot(my_data_1, "mo-", label="my data 1") pyplot.plot(my_data_2, "bo-", label="my data 2")
will plot my_data_1
in magenta and my_data_2
in blue on the same figure.
Supply labels for your plots, like above. Then use pyplot.legend
to give your graph a legend. Just plain pyplot.legend()
will work, but providing more options may give a better effect.
Your graph should look something like this:
To save your graph to a file instead of or in addition to displaying it, call pyplot.savefig
.
Life expectancy resources:
- File input and output: http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files.
- Splitting sprints into parts based on a delimiter: http://www.hacksparrow.com/python-split-string-method-and-examples.html
- Examples of legends: http://matplotlib.sourceforge.net/examples/pylab_examples/legend_auto.html
- Ways to configure your legend: http://matplotlib.sourceforge.net/api/legend_api.html
- Saving your graph to a file: http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.savefig
Bonus exercises
1. Letter frequency analysis of the US Constitution
- Run
python constitution.py
. It will generate a bar chart showing the frequency of each letter in the alphabet in the US Constitution. - Open and read through
constitution.py
. The code for gathering and displaying the frequencies is a bit more complicated than the previous scripts in this projects, but try to trace the general strategy for plotting the data. Be sure to read the comments! - Try to answer the following questions:
- On line 11, what is
string.ascii_lowercase
? - On line 18, what is the purpose of
char = char.lower()
? - What are the contents of
labels
after thefor
loop on line 30 completes? - On line 41, what are the two arguments passed to
pyplot.xticks
- On line 44, we use
pyplot.bar
instead of our usualpyplot.plot
. What are the 3 arguments passed topyplot.bar
?
- On line 11, what is
- We've included a mystery text file
mystery.txt
: an excerpt from an actual novel. Alterconstitution.py
to process the data inmystery.txt
instead ofconstitution.txt
, and re-run the script. What do you notice that is odd about this file? You can read more about this odd novel here.
2. Tour the matplotlib gallery
You can truly make any kind of graph with matplotlib. You can even create animated graphs. Check out some of the amazing possibilities, including their source code, at the matplotlib gallery: http://matplotlib.sourceforge.net/gallery.html.
Congratulations!
You've read, modified, and created scripts that plot and analyze data using matplotlib. Keep practicing!