Skip to content

Instantly share code, notes, and snippets.

@jonathanmorgan
Last active January 12, 2017 11:30
Show Gist options
  • Save jonathanmorgan/dccb1891d5f83c9923b9 to your computer and use it in GitHub Desktop.
Save jonathanmorgan/dccb1891d5f83c9923b9 to your computer and use it in GitHub Desktop.
Visualization in Python using matplotlib
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# matplotlib - visualization in Python"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"_Based on http://nbviewer.ipython.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-4-Matplotlib.ipynb by J.R. Johansson (robert@riken.jp) [http://dml.riken.jp/~rob/](http://dml.riken.jp/~rob/). Source for the original and other lessons are available at [http://github.com/jrjohansson/scientific-python-lectures](http://github.com/jrjohansson/scientific-python-lectures)._"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Table of Contents\n",
"\n",
"- [Setup](#Setup)\n",
"- [Introduction](#Introduction)\n",
"- [The basics - introducing the matplotlib object-oriented API](#The-basics---introducing-the-matplotlib-object-oriented-API)\n",
"\n",
" - [A note on matplotlib figures and memory](#A-note-on-matplotlib-figures-and-memory)\n",
" - [More information on `matplotlib`](#More-information-on-matplotlib)\n",
" \n",
"- [Advanced layouts using axis layout managers](#Advanced-layouts-using-axis-layout-managers)\n",
"- [Figure size, aspect ratio and DPI](#Figure-size,-aspect-ratio-and-DPI)\n",
"- [Saving figures](#Saving-figures)\n",
"\n",
" - [Available formats for saved files](#Available-formats-for-saved-files)\n",
" \n",
"- [Formatting](#Formatting)\n",
"\n",
" - [Legends, labels and titles](#Legends,-labels-and-titles)\n",
" - [Formatting text - LaTeX, fontsize, font-family](#Formatting-text---LaTeX,-fontsize,-font-family)\n",
" - [Setting colors, linewidths, linetypes](#Setting-colors,-linewidths,-linetypes)\n",
" \n",
" - [Colors](#Colors)\n",
" - [Line and marker styles](#Line-and-marker-styles)\n",
" \n",
" - [Control over axis appearance, range, and scale](#Control-over-axis-appearance,-range,-and-scale)\n",
" \n",
" - [Plot range](#Plot-range)\n",
" - [Placement of ticks and custom tick labels](#Placement-of-ticks-and-custom-tick-labels)\n",
" - [Axis grid](#Axis-grid)\n",
" - [Axis spines](#Axis-spines)\n",
" - [Twin axes](#Twin-axes)\n",
" - [Axes where x and y are zero](#Axes-where-x-and-y-are-zero)\n",
" \n",
" - [Other 2D plot styles](#Other-2D-plot-styles)\n",
" - [Text annotation](#Text-annotation)\n",
" \n",
"- [`matplotlib` rendering backends](#matplotlib-rendering-backends)\n",
"\n",
" - [Generating SVG with the `svg` backend](#Generating-SVG-with-the-svg-backend)\n",
" - [The jupyter-IPython notebook `inline` backend](#The-jupyter-IPython-notebook-inline-backend)\n",
" - [Interactive backend](#Interactive-backend)\n",
" \n",
"- [Further reading](#Further-reading)\n",
"\n",
" - [`matplotlib` Tutorials](#matplotlib-Tutorials)\n",
" - [`matplotlib` Documentation](#matplotlib-Documentation)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Setup\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Before we begin, we'll need to import the matplotlib python package and do a few other configuration steps."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# first, import matplotlib, namespacing it as plt\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# import numpy so we can use numpy's numeric lists\n",
"import numpy\n",
"\n",
"# This line configures matplotlib to show figures embedded in the notebook, \n",
"# instead of opening a new window for each figure. More about that later. \n",
"%matplotlib inline\n",
"\n",
"# If you are using an old version of IPython, try using '%pylab inline' instead.\n",
"# If you want the figures to pop up in their own windows, don't do the above."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Matplotlib is an excellent 2D and 3D graphics library for generating scientific figures. Some of the many advantages of this library include:\n",
"\n",
"* Easy to get started\n",
"* Support for $\\LaTeX$ formatted labels and texts\n",
"* Great control of every element in a figure, including figure size and DPI. \n",
"* High-quality output in many formats, including PNG, PDF, SVG, EPS, and PGF.\n",
"* GUI for interactively exploring figures *and* support for headless generation of figure files (useful for batch jobs).\n",
"\n",
"One of the of the key features of matplotlib is that all aspects of the figure can be controlled *programmatically*. This is important for reproducibility and convenient when one needs to regenerate a figure for multiple sets of similar data, or the same figure but with updated data, or simply to change the appearance of an existing figure.\n",
"\n",
"In practical terms, being able to make code files that capture how you made your figures is also practically indispensible if you are rapidly iterating figures on a deadline, or want to keep track of not just the figures in a paper but how you rendered them in case you need to re-render because of changes based on reviews or subsequent work.\n",
"\n",
"More information at the Matplotlib web page: http://matplotlib.org/"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# The basics - introducing the matplotlib object-oriented API\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"The term \"object-oriented\" refers to a style of programming where you use objects that hold variables and can be interacted with throughout your program. In the code we've been working with, things like database cursors, dictionaries, and http responses have been instances of objects. Objects contain variables that reflect the state of a given instance of the object, and then functions that are designed to work specifically with the object.\n",
"\n",
"In matplotlib, the object one makes instances of and interacts with is a plot - a canvas (in 2D terms) on which you can lay down axes, labels, and titles, and then plot one or more sets of points, and which you can then set display properties in to control the type of graph or diagram that results when the plot is rendered. This allows you to layer graphs of multiple sets of points within a given plot, or plot multiple figures side-by-side.\n",
"\n",
"To get started using the object-oriented matplotlib API, we'll first create lists of X and Y coordinates:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# create a set of 10 X values\n",
"x = [ 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5 ]\n",
"\n",
"# create separate list of Y values that is each X value squared.\n",
"y = []\n",
"for current_x in x:\n",
" \n",
" # append squared value to y\n",
" y.append( current_x ** 2 )\n",
" \n",
"#-- END loop over x value list --#"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We'll then create a matplotlib figure() instance (our canvas), plot our points, add some axes to the plot, and configure the axes to have labels and a title at the top:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# create a matplotlib figure (our canvas)\n",
"fig = plt.figure()\n",
"\n",
"# make a set of axes\n",
"axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)\n",
"\n",
"# plot our x and y values in \"r\"ed.\n",
"axes.plot(x, y, 'r')\n",
"\n",
"# add labels and a title to the axes.\n",
"axes.set_xlabel('x')\n",
"axes.set_ylabel('y')\n",
"axes.set_title('title');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Although a little bit more code is involved, the advantage is that we now have full control of where the plot axes are placed, and we can easily add plots to the figure (causing the scale of the graph to adjust accordingly):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# create a matplotlib figure (our canvas)\n",
"fig = plt.figure()\n",
"\n",
"# make a set of axes\n",
"axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)\n",
"\n",
"# plot our x and y values in \"r\"ed.\n",
"axes.plot(x, y, 'r')\n",
"\n",
"# and plot the inverse (x as y, and y as x) in \"g\"reen.\n",
"axes.plot(y, x, 'g')\n",
"\n",
"# add labels and a title to the axes.\n",
"axes.set_xlabel('x')\n",
"axes.set_ylabel('y')\n",
"axes.set_title('title');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Or, to keep the figure from getting skewed, add more than one axis to the figure, and place our second figure within the second set of axes:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig = plt.figure()\n",
"\n",
"axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes\n",
"axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes\n",
"\n",
"# main figure\n",
"axes1.plot(x, y, 'r')\n",
"axes1.set_xlabel('x')\n",
"axes1.set_ylabel('y')\n",
"axes1.set_title('title')\n",
"\n",
"# insert\n",
"axes2.plot(y, x, 'g')\n",
"axes2.set_xlabel('y')\n",
"axes2.set_ylabel('x')\n",
"axes2.set_title('inverse title');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A note on matplotlib figures and memory\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"> \"If you are making a long sequence of figures, you need to be aware of one more thing: the memory required for a figure is not completely released until the figure is explicitly closed with close(). Deleting all references to the figure, and/or using the window manager to kill the window in which the figure appears on the screen, is not enough, because pyplot maintains internal references until close() is called.\"\n",
"\n",
"> — from: [http://matplotlib.org/users/pyplot_tutorial.html](http://matplotlib.org/users/pyplot_tutorial.html)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## More information on `matplotlib`\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"For more detailed information on matplotlib, see:\n",
"\n",
"- [http://matplotlib.org/api/figure_api.html](http://matplotlib.org/api/figure_api.html) - Detailed documentation on the matplotlib figure object.\n",
"- [http://matplotlib.org/api/axis_api.html](http://matplotlib.org/api/axis_api.html) - Detailed documentation on the matplotlib axis object."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Advanced layouts using axis layout managers\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"As one starts to make more complicated layouts of figures (multiple graphs in a given figure, for example), the complexity of building and arranging all of the axes oneself can outweigh the control this gives you. If you are willing to trade complete control over your layout for simplicity, you can use one of the many axis layout managers in matplotlib to create more complex graphs, including figures with multiple plots side. One example is `subplots`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# use subplots() function to get a figure and a ready-made axis object.\n",
"fig, axes = plt.subplots()\n",
"\n",
"# plot our X and Y values using the predefined axis.\n",
"# by default, returns a single axis.\n",
"axes.plot(x, y, 'r')\n",
"axes.set_xlabel('x')\n",
"axes.set_ylabel('y')\n",
"axes.set_title('title');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"While subplots() can be used to make you a single axis, it can also be used to build you a matrix of axes within your figure, returning the axes as a list that you can iterate over:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# use subplots() function to get a figure and a ready-made list of axis objects.\n",
"fig, axes = plt.subplots( nrows = 1, ncols = 2 )\n",
"\n",
"# to start, for each axis, plot our x/y coordinates.\n",
"for ax in axes:\n",
" ax.plot(x, y, 'r')\n",
" ax.set_xlabel('x')\n",
" ax.set_ylabel('y')\n",
" ax.set_title('title')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"That was easy, but it isn't so pretty with overlapping figure axes and labels, right?\n",
"\n",
"We can deal with that by using the `fig.tight_layout` method, which automatically adjusts the positions of the axes on the figure canvas so that there is no overlapping content:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# use subplots() function to get a figure and a ready-made list of axis objects.\n",
"fig, axes = plt.subplots( nrows = 1, ncols = 2 )\n",
"\n",
"# to start, for each axis, plot our x/y coordinates.\n",
"for ax in axes:\n",
" ax.plot(x, y, 'r')\n",
" ax.set_xlabel('x')\n",
" ax.set_ylabel('y')\n",
" ax.set_title('title')\n",
"\n",
"# let matplotlib automatically adjust the layout so there is no overlap.\n",
"fig.tight_layout()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also interact with the individual axes by referencing their position in the list returned by subplots():"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# use subplots() function to get a figure and a ready-made list of axis objects.\n",
"fig, axes = plt.subplots( nrows = 1, ncols = 2 )\n",
"\n",
"# to start, plot our x/y coordinates.\n",
"current_axis = axes[ 0 ]\n",
"current_axis.plot( x, y, 'r' )\n",
"current_axis.set_xlabel( 'x' )\n",
"current_axis.set_ylabel( 'y' )\n",
"current_axis.set_title( 'title' )\n",
"\n",
"# to start, plot the inverse.\n",
"current_axis = axes[ 1 ]\n",
"current_axis.plot( y, x, 'g' )\n",
"current_axis.set_xlabel( 'y' )\n",
"current_axis.set_ylabel( 'x' )\n",
"current_axis.set_title( 'inverse title' )\n",
"\n",
"# let matplotlib automatically adjust the layout so there is no overlap.\n",
"fig.tight_layout()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you request more than one row, subplots() will return a list of lists of axes, so you'll have to first get the row you want, which will contain a list of the axes in the row, and then you'll have to choose an axis from that list of the row's axes:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# use subplots() function to get a figure and a ready-made list of axis objects.\n",
"fig, axes = plt.subplots( nrows = 2, ncols = 2 )\n",
"\n",
"# first row (remember that Python lists are 0-indexed):\n",
"current_row = axes[ 0 ]\n",
"\n",
"# to start, plot our x/y coordinates.\n",
"current_axis = current_row[ 0 ]\n",
"current_axis.plot( x, y, 'r' )\n",
"current_axis.set_xlabel( 'x' )\n",
"current_axis.set_ylabel( 'y' )\n",
"current_axis.set_title( 'title' )\n",
"\n",
"# plot the inverse.\n",
"current_axis = current_row[ 1 ]\n",
"current_axis.plot( y, x, 'g' )\n",
"current_axis.set_xlabel( 'y' )\n",
"current_axis.set_ylabel( 'x' )\n",
"current_axis.set_title( 'inverse title' )\n",
"\n",
"# second row (remember that Python lists are 0-indexed):\n",
"current_row = axes[ 1 ]\n",
"\n",
"# the reverse! to start, plot the inverse.\n",
"current_axis = current_row[ 0 ]\n",
"current_axis.plot( x, y, 'r' )\n",
"current_axis.set_xlabel( 'x' )\n",
"current_axis.set_ylabel( 'y' )\n",
"current_axis.set_title( 'title' )\n",
"\n",
"# plot our x/y coordinates.\n",
"current_axis = current_row[ 1 ]\n",
"current_axis.plot( y, x, 'g' )\n",
"current_axis.set_xlabel( 'y' )\n",
"current_axis.set_ylabel( 'x' )\n",
"current_axis.set_title( 'inverse title' )\n",
"\n",
"# let matplotlib automatically adjust the layout so there is no overlap.\n",
"fig.tight_layout()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Figure size, aspect ratio and DPI\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Matplotlib allows the aspect ratio, DPI and figure size to be specified when the `Figure` object is created, using the `figsize` and `dpi` keyword arguments. `figsize` is a tuple of the width and height of the figure in inches, and `dpi` is the dots-per-inch (pixel per inch). To create an 800x400 pixel, 100 dots-per-inch figure, we can do: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig = plt.figure( figsize = ( 8, 4 ), dpi = 100 )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The same arguments can also be passed to layout managers, such as the `subplots` function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, axes = plt.subplots( figsize= ( 12, 3 ) )\n",
"\n",
"axes.plot( x, y, 'r' )\n",
"axes.set_xlabel( 'x' )\n",
"axes.set_ylabel( 'y' )\n",
"axes.set_title( 'title' );"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's use these arguments to give our 4-axis plot a little more room to breathe:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# use subplots() function to get a figure and a ready-made list of axis objects.\n",
"fig, axes = plt.subplots( nrows = 2, ncols = 2, figsize = ( 8, 8 ), dpi = 100 )\n",
"\n",
"# first row (remember that Python lists are 0-indexed):\n",
"current_row = axes[ 0 ]\n",
"\n",
"# to start, plot our x/y coordinates.\n",
"current_axis = current_row[ 0 ]\n",
"current_axis.plot( x, y, 'r' )\n",
"current_axis.set_xlabel( 'x' )\n",
"current_axis.set_ylabel( 'y' )\n",
"current_axis.set_title( 'title' )\n",
"\n",
"# plot the inverse.\n",
"current_axis = current_row[ 1 ]\n",
"current_axis.plot( y, x, 'g' )\n",
"current_axis.set_xlabel( 'y' )\n",
"current_axis.set_ylabel( 'x' )\n",
"current_axis.set_title( 'inverse title' )\n",
"\n",
"# second row (remember that Python lists are 0-indexed):\n",
"current_row = axes[ 1 ]\n",
"\n",
"# the reverse! to start, plot the inverse.\n",
"current_axis = current_row[ 0 ]\n",
"current_axis.plot( x, y, 'r' )\n",
"current_axis.set_xlabel( 'x' )\n",
"current_axis.set_ylabel( 'y' )\n",
"current_axis.set_title( 'title' )\n",
"\n",
"# plot our x/y coordinates.\n",
"current_axis = current_row[ 1 ]\n",
"current_axis.plot( y, x, 'g' )\n",
"current_axis.set_xlabel( 'y' )\n",
"current_axis.set_ylabel( 'x' )\n",
"current_axis.set_title( 'inverse title' )\n",
"\n",
"# let matplotlib automatically adjust the layout so there is no overlap.\n",
"fig.tight_layout()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Saving figures\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"To save a figure to a file we can use the `savefig` method in the `Figure` class:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig.savefig( \"filename.png\" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we can also optionally specify the DPI and choose between different output formats:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig.savefig( \"filename.pdf\", dpi = 200, format = \"pdf\" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Available formats for saved files\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Matplotlib can generate high-quality output in a number formats, including PNG, JPG, EPS, SVG, PGF and PDF.\n",
"\n",
"`format` defaults to `None`, can be set to one of the file extensions supported by the active backend. Most backends support:\n",
"\n",
"- `png` - PNG image format.\n",
"- `pdf` - Adobe Portable Document Format.\n",
"- `ps` - PostScript\n",
"- `eps` - Encapsulated PostScript\n",
"- `svg` - Scalable Vector Graphics image format."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Formatting\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"## Legends, labels and titles\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Now that we have covered the basics of how to create a figure canvas and add axes instances to the canvas, let's look in more detail at how decorate a figure with titles, axis labels, and legends."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Figure titles**\n",
"\n",
"A title can be added to each axis instance in a figure. To set the title, use the `set_title` method in the axes instance:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ax.set_title(\"title\");"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Axis labels**\n",
"\n",
"Similarly, with the methods `set_xlabel` and `set_ylabel`, we can set the labels of the X and Y axes:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ax.set_xlabel(\"x\")\n",
"ax.set_ylabel(\"y\");"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Legends**\n",
"\n",
"Legends for curves in a figure can be added using the `label=\"label text\"` keyword argument when plots or other objects are added to the figure, and then using the `legend()` method without arguments to add the legend to the figure: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ax.plot( x, y, label = \"plot1\" )\n",
"ax.plot( y, x, label = \"plot2\" )\n",
"ax.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As curves are added or removed from the figure, the `legend()` method automatically updates the legend accordingly.\n",
"\n",
"The `legend()` function takes an optional keyword argument `loc` that can be used to specify where in the figure the legend is to be drawn. The allowed values of `loc` are numerical codes for the various places the legend can be drawn. See http://matplotlib.org/users/legend_guide.html#legend-location for details. Some of the most common `loc` values are:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"ax.legend( loc = 0 ) # let matplotlib decide the optimal location\n",
"ax.legend( loc = 1 ) # upper right corner\n",
"ax.legend( loc = 2 ) # upper left corner\n",
"ax.legend( loc = 3 ) # lower left corner\n",
"ax.legend( loc = 4 ) # lower right corner\n",
"# .. many more options are available"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following figure shows how to use the figure title, axis labels and legends described above:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# create figure and axis\n",
"fig, axis = plt.subplots()\n",
"\n",
"# add a couple of plots\n",
"axis.plot( x, y, label = \"y = x**2\" )\n",
"axis.plot( x, x, label = \"y = x\" )\n",
"\n",
"# create legend\n",
"axis.legend( loc = 2 ); # upper left corner\n",
"\n",
"# add labels and title.\n",
"axis.set_xlabel('x')\n",
"axis.set_ylabel('y')\n",
"axis.set_title('title');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Formatting text - LaTeX, fontsize, font family\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"The figure above is functional, but it does not (yet) satisfy the criteria for a figure used in a publication. First and foremost, we need to have LaTeX formatted text, and second, we need to be able to adjust the font size to appear right in a publication.\n",
"\n",
"Matplotlib has great support for LaTeX. All we need to do is to use dollar signs encapsulate LaTeX in any text (legend, title, label, etc.). For example, `\"$y=x^3$\"`.\n",
"\n",
"But here we can run into a slightly subtle problem with LaTeX code and Python text strings. In LaTeX, we frequently use the backslash in commands, for example `\\alpha` to produce the symbol $\\alpha$. But the backslash already has a meaning in Python strings (the escape code character). To avoid Python messing up our latex code, we need to use \"raw\" text strings. Raw text strings are prepended with an '`r`', like `r\"\\alpha\"` or `r'\\alpha'` instead of `\"\\alpha\"` or `'\\alpha'`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# get figure and axis\n",
"fig, axis = plt.subplots()\n",
"\n",
"# use latex to output pretty equations instead of plain text.\n",
"axis.plot( x, y, label = r\"$y = \\alpha^2$\" )\n",
"axis.plot( x, x, label = r\"$y = \\alpha$\" )\n",
"\n",
"# position axis\n",
"axis.legend(loc=2) # upper left corner\n",
"\n",
"# use alpha in labels, as well, and make it bigger.\n",
"axis.set_xlabel( r'$\\alpha$', fontsize = 18 )\n",
"axis.set_ylabel( r'$y$', fontsize = 18 )\n",
"axis.set_title( 'title' );"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also change the global font size and font family, which applies to all text elements in a figure (tick labels, axis labels and titles, legends, etc.):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Update the matplotlib configuration parameters:\n",
"matplotlib.rcParams.update( { 'font.size' : 18, 'font.family' : 'serif' } )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# get figure and axis\n",
"fig, axis = plt.subplots()\n",
"\n",
"# use latex to output pretty equations instead of plain text.\n",
"axis.plot( x, y, label = r\"$y = \\alpha^2$\" )\n",
"axis.plot( x, x, label = r\"$y = \\alpha$\" )\n",
"\n",
"# position axis\n",
"axis.legend(loc=2) # upper left corner\n",
"\n",
"# use alpha in labels, as well, and make it bigger.\n",
"axis.set_xlabel( r'$\\alpha$', fontsize = 18 )\n",
"axis.set_ylabel( r'$y$', fontsize = 18 )\n",
"axis.set_title( 'title' );"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One choice for global fonts is the STIX fonts: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Update the matplotlib configuration parameters:\n",
"matplotlib.rcParams.update({'font.size': 18, 'font.family': 'STIXGeneral', 'mathtext.fontset': 'stix'})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# get figure and axis\n",
"fig, axis = plt.subplots()\n",
"\n",
"# use latex to output pretty equations instead of plain text.\n",
"axis.plot( x, y, label = r\"$y = \\alpha^2$\" )\n",
"axis.plot( x, x, label = r\"$y = \\alpha$\" )\n",
"\n",
"# position axis\n",
"axis.legend(loc=2) # upper left corner\n",
"\n",
"# use alpha in labels, as well, and make it bigger.\n",
"axis.set_xlabel( r'$\\alpha$', fontsize = 18 )\n",
"axis.set_ylabel( r'$y$', fontsize = 18 )\n",
"axis.set_title( 'title' );"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# restore to 12-point sans\n",
"matplotlib.rcParams.update( { 'font.size' : 12, 'font.family' : 'sans', 'text.usetex': False } )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setting colors, linewidths, linetypes\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"### Colors\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"We can define colors for plots by color names or RGB hex codes using the `color` keyword argument, and can optionally provide an alpha value (transparency percentage) using the `alpha` keyword arguments:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# create figure and axis\n",
"fig, axis = plt.subplots()\n",
"\n",
"# add a couple of plots\n",
"axis.plot( x, y, label = \"y = x**2\", color = \"red\", alpha = 0.5 ) # half-transparant red\n",
"axis.plot( x, x, label = \"y = x\", color = \"#1155dd\" ) # RGB hex code for a bluish color\n",
"\n",
"# create legend\n",
"axis.legend( loc = 2 ); # upper left corner\n",
"\n",
"# add labels and title.\n",
"axis.set_xlabel('x')\n",
"axis.set_ylabel('y')\n",
"axis.set_title('title');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Line and marker styles\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"To change the line width, we can use the `linewidth` or `lw` keyword argument. The line style can be selected using the `linestyle` or `ls` keyword arguments:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# use numpy to create list of numbers for x values\n",
"x = numpy.linspace(0, 5, 10)\n",
"y = x ** 2\n",
"\n",
"# create a figure and an axis.\n",
"fig, ax = plt.subplots(figsize=(12,6))\n",
"\n",
"# lots of plots to show different line options!\n",
"ax.plot(x, x+1, color=\"blue\", linewidth=0.25)\n",
"ax.plot(x, x+2, color=\"blue\", linewidth=0.50)\n",
"ax.plot(x, x+3, color=\"blue\", linewidth=1.00)\n",
"ax.plot(x, x+4, color=\"blue\", linewidth=2.00)\n",
"\n",
"# possible linestype options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’\n",
"ax.plot(x, x+5, color=\"red\", lw=2, linestyle='-')\n",
"ax.plot(x, x+6, color=\"red\", lw=2, ls='-.')\n",
"ax.plot(x, x+7, color=\"red\", lw=2, ls=':')\n",
"\n",
"# custom dash\n",
"line, = ax.plot(x, x+8, color=\"black\", lw=1.50)\n",
"line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...\n",
"\n",
"# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...\n",
"ax.plot(x, x+ 9, color=\"green\", lw=2, ls='*', marker='+')\n",
"ax.plot(x, x+10, color=\"green\", lw=2, ls='*', marker='o')\n",
"ax.plot(x, x+11, color=\"green\", lw=2, ls='*', marker='s')\n",
"ax.plot(x, x+12, color=\"green\", lw=2, ls='*', marker='1')\n",
"\n",
"# marker size and color\n",
"ax.plot(x, x+13, color=\"purple\", lw=1, ls='-', marker='o', markersize=2)\n",
"ax.plot(x, x+14, color=\"purple\", lw=1, ls='-', marker='o', markersize=4)\n",
"ax.plot(x, x+15, color=\"purple\", lw=1, ls='-', marker='o', markersize=8, markerfacecolor=\"red\")\n",
"ax.plot(x, x+16, color=\"purple\", lw=1, ls='-', marker='s', markersize=8, \n",
" markerfacecolor=\"yellow\", markeredgewidth=2, markeredgecolor=\"blue\");"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Control over axis appearance, range, and scale\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"When preparing a graphic for publication, it is important to be able to control where the ticks and labels are placed, modify the font size and possibly the labels used on the axes. In this section we will look at controling those properties in a matplotlib figure."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Plot range\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"The first thing we might want to configure is the ranges of the axes. We can do this using the `set_ylim` and `set_xlim` methods in the axis object, or `axis('tight')` for automatrically getting \"tightly fitted\" axes ranges:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# generate figure and 3 axes.\n",
"fig, axes = plt.subplots( 1, 3, figsize=( 12, 4 ) )\n",
"\n",
"# standard layout\n",
"axes[ 0 ].plot( x, x**2 )\n",
"axes[ 0 ].plot( x, x**3 )\n",
"axes[ 0 ].set_title( \"default axes ranges\" )\n",
"\n",
"# use axis( \"tight\" ) to minimize white space in axis.\n",
"axes[ 1 ].plot( x, x**2 )\n",
"axes[ 1 ].plot( x, x**3 )\n",
"axes[ 1 ].axis( 'tight' )\n",
"axes[ 1 ].set_title( \"tight axes\" )\n",
"\n",
"# explicitly specify the range of values that will be visible in the axis.\n",
"axes[ 2 ].plot( x, x**2 )\n",
"axes[ 2 ].plot( x, x**3 )\n",
"axes[ 2 ].set_ylim( [ 0, 60 ] )\n",
"axes[ 2 ].set_xlim( [ 2, 5 ] )\n",
"axes[ 2 ].set_title( \"custom axes range\" );"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Placement of ticks and custom tick labels\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"We can explicitly determine where we want the axis ticks with `set_xticks` and `set_yticks`, which both take a list of values for where on the axis the ticks are to be placed. We can also use the `set_xticklabels` and `set_yticklabels` methods to provide a list of custom text labels for each tick location:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# create figure and axis.\n",
"fig, axis = plt.subplots( figsize = ( 10, 4 ) )\n",
"\n",
"# add a couple of plots\n",
"axis.plot( x, x**2 )\n",
"axis.plot( x, x**3, lw = 2 )\n",
"\n",
"# set ticks and tick labels (greek letters!)\n",
"axis.set_xticks( [ 1, 2, 3, 4, 5 ] ) # 5 ticks on X-axis\n",
"axis.set_xticklabels( [ r'$\\alpha$', r'$\\beta$', r'$\\gamma$', r'$\\delta$', r'$\\epsilon$' ], fontsize = 18 )\n",
"\n",
"# and the Y-axis\n",
"yticks = [ 0, 50, 100, 150 ]\n",
"axis.set_yticks( yticks )\n",
"\n",
"tick_label_list = []\n",
"for current_value in yticks:\n",
" tick_label_list.append( \"$\" + str( current_value) + \".1f$\" ) # LaTeX formatting...\n",
"#-- END loop over ticks to make labels --#\n",
"\n",
"axis.set_yticklabels( tick_label_list, fontsize = 18 ); # use LaTeX formatted labels"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are a number of more advanced methods for controlling major and minor tick placement in matplotlib figures, such as automatic placement according to different policies. See http://matplotlib.org/api/ticker_api.html for details."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Axis grid\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"With the `grid` method in the axis object, we can turn on and off grid lines. We can also customize the appearance of the grid lines using the same keyword arguments as the `plot` function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, axes = plt.subplots(1, 2, figsize=(10,3))\n",
"\n",
"# default grid appearance\n",
"axes[0].plot(x, x**2, x, x**3, lw=2)\n",
"axes[0].grid(True)\n",
"\n",
"# custom grid appearance\n",
"axes[1].plot(x, x**2, x, x**3, lw=2)\n",
"axes[1].grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Axis spines\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"We can also change the properties of axis spines:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(6,2))\n",
"\n",
"ax.spines['bottom'].set_color('blue')\n",
"ax.spines['top'].set_color('blue')\n",
"\n",
"ax.spines['left'].set_color('red')\n",
"ax.spines['left'].set_linewidth(2)\n",
"\n",
"# turn off axis spine to the right\n",
"ax.spines['right'].set_color(\"none\")\n",
"ax.yaxis.tick_left() # only ticks on the left side"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Twin axes\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Sometimes it is useful to have dual x or y axes in a figure; for example, when plotting curves with different units together. Matplotlib supports this with the `twinx` and `twiny` functions:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax1 = plt.subplots()\n",
"\n",
"ax1.plot(x, x**2, lw=2, color=\"blue\")\n",
"ax1.set_ylabel(r\"area $(m^2)$\", fontsize=18, color=\"blue\")\n",
"for label in ax1.get_yticklabels():\n",
" label.set_color(\"blue\")\n",
" \n",
"ax2 = ax1.twinx()\n",
"ax2.plot(x, x**3, lw=2, color=\"red\")\n",
"ax2.set_ylabel(r\"volume $(m^3)$\", fontsize=18, color=\"red\")\n",
"for label in ax2.get_yticklabels():\n",
" label.set_color(\"red\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Axes where x and y are zero\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"\n",
"ax.spines['right'].set_color('none')\n",
"ax.spines['top'].set_color('none')\n",
"\n",
"ax.xaxis.set_ticks_position('bottom')\n",
"ax.spines['bottom'].set_position(('data',0)) # set position of x spine to x=0\n",
"\n",
"ax.yaxis.set_ticks_position('left')\n",
"ax.spines['left'].set_position(('data',0)) # set position of y spine to y=0\n",
"\n",
"xx = np.linspace(-0.75, 1., 100)\n",
"ax.plot(xx, xx**3);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Other 2D plot styles\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"In addition to the regular `plot` method, there are a number of other functions for generating different kind of plots. See the matplotlib plot gallery for a complete list of available plot types: http://matplotlib.org/gallery.html. Some of the more useful ones are show below:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"n = array([0,1,2,3,4,5])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, axes = plt.subplots(1, 4, figsize=(12,3))\n",
"\n",
"axes[0].scatter(xx, xx + 0.25*randn(len(xx)))\n",
"axes[0].set_title(\"scatter\")\n",
"\n",
"axes[1].step(n, n**2, lw=2)\n",
"axes[1].set_title(\"step\")\n",
"\n",
"axes[2].bar(n, n**2, align=\"center\", width=0.5, alpha=0.5)\n",
"axes[2].set_title(\"bar\")\n",
"\n",
"axes[3].fill_between(x, x**2, x**3, color=\"green\", alpha=0.5);\n",
"axes[3].set_title(\"fill_between\");"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# polar plot using add_axes and polar projection\n",
"fig = plt.figure()\n",
"ax = fig.add_axes([0.0, 0.0, .6, .6], polar=True)\n",
"t = linspace(0, 2 * pi, 100)\n",
"ax.plot(t, t, color='blue', lw=3);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# A histogram\n",
"n = np.random.randn(100000)\n",
"fig, axes = plt.subplots(1, 2, figsize=(12,4))\n",
"\n",
"axes[0].hist(n)\n",
"axes[0].set_title(\"Default histogram\")\n",
"axes[0].set_xlim((min(n), max(n)))\n",
"\n",
"axes[1].hist(n, cumulative=True, bins=50)\n",
"axes[1].set_title(\"Cumulative detailed histogram\")\n",
"axes[1].set_xlim((min(n), max(n)));"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Text annotation\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Annotating text in matplotlib figures can be done using the `text` function. It supports LaTeX formatting just like axis label texts and titles:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"\n",
"ax.plot(xx, xx**2, xx, xx**3)\n",
"\n",
"ax.text(0.15, 0.2, r\"$y=x^2$\", fontsize=20, color=\"blue\")\n",
"ax.text(0.65, 0.1, r\"$y=x^3$\", fontsize=20, color=\"green\");"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# `matplotlib` rendering backends\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Matplotlib has a number of \"backends\" which are responsible for rendering graphs. The different backends are able to generate graphics with different formats and display/event loops. There is a distinction between noninteractive backends (such as 'agg', 'svg', 'pdf', etc.) that are only used to generate image files (e.g. with the `savefig` function), and interactive backends (such as Qt4Agg, GTK, MaxOSX) that can display a GUI window for interactively exploring figures. \n",
"\n",
"A list of available backends are:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(matplotlib.rcsetup.all_backends)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The default backend, called `agg`, is based on a library for raster graphics which is great for generating raster formats like PNG.\n",
"\n",
"Normally we don't need to bother with changing the default backend; but sometimes it can be useful to switch to, for example, PDF or GTKCairo (if you are using Linux) to produce high-quality vector graphics instead of raster based graphics. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Generating SVG with the `svg` backend\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#\n",
"# RESTART THE NOTEBOOK: the matplotlib backend can only be selected before pylab is imported!\n",
"# (e.g. Kernel > Restart)\n",
"# \n",
"import matplotlib\n",
"matplotlib.use('svg')\n",
"import matplotlib.pylab as plt\n",
"import numpy\n",
"from IPython.display import Image, SVG"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#\n",
"# Now we are using the svg backend to produce SVG vector graphics\n",
"#\n",
"fig, ax = plt.subplots()\n",
"t = numpy.linspace(0, 10, 100)\n",
"ax.plot(t, numpy.cos(t)*numpy.sin(t))\n",
"plt.savefig(\"test.svg\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#\n",
"# Show the produced SVG file. \n",
"#\n",
"SVG(filename=\"test.svg\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The jupyter-IPython notebook `inline` backend\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"When we use IPython notebook it is convenient to use a matplotlib backend that outputs the graphics embedded in the notebook file. To activate this backend, somewhere in the beginning on the notebook, we add:\n",
"\n",
" %matplotlib inline\n",
"\n",
"It is also possible to activate inline matplotlib plotting with:\n",
"\n",
" %pylab inline\n",
"\n",
"The difference is that `%pylab inline` imports a number of packages into the global address space (scipy, numpy), while `%matplotlib inline` only sets up inline plotting. In new notebooks created for IPython 1.0+, I would recommend using `%matplotlib inline`, since it is tidier and you have more control over which packages are imported and how. Commonly, scipy and numpy are imported separately with:\n",
"\n",
" import numpy as np\n",
" import scipy as sp\n",
" import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The inline backend has a number of configuration options that can be set by using the IPython magic command `%config` to update settings in `InlineBackend`. For example, we can switch to SVG figures or higher resolution figures with either:\n",
"\n",
" %config InlineBackend.figure_format='svg'\n",
" \n",
"or:\n",
"\n",
" %config InlineBackend.figure_format='retina'\n",
" \n",
"For more information, type:\n",
"\n",
" %config InlineBackend"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"%config InlineBackend.figure_format='svg'\n",
"\n",
"import matplotlib.pylab as plt\n",
"import numpy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#\n",
"# Now we are using the SVG vector graphics displaced inline in the notebook\n",
"#\n",
"fig, ax = plt.subplots()\n",
"t = numpy.linspace(0, 10, 100)\n",
"ax.plot(t, numpy.cos(t)*numpy.sin(t))\n",
"plt.savefig(\"test.svg\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Interactive backend\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"This make more sense in a python script file, rather than in an ipython notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#\n",
"# RESTART THE NOTEBOOK: the matplotlib backend can only be selected before pylab is imported!\n",
"# (e.g. Kernel > Restart)\n",
"# \n",
"import matplotlib\n",
"matplotlib.use('Qt4Agg') # or for example MacOSX\n",
"import matplotlib.pylab as plt\n",
"import numpy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Now, open an interactive plot window with the Qt4Agg backend\n",
"fig, ax = plt.subplots()\n",
"t = numpy.linspace(0, 10, 100)\n",
"ax.plot(t, numpy.cos(t)*numpy.sin(t))\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that when we use an interactive backend, we must call `plt.show()` to make the figure appear on the screen."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Further reading\n",
"\n",
"- Back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"## `matplotlib` Tutorials\n",
"\n",
"- [http://nbviewer.ipython.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-4-Matplotlib.ipynb](http://nbviewer.ipython.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-4-Matplotlib.ipynb) - The full original presentation on which this is based (includes 3D figures!).\n",
"- [https://scipy-lectures.github.io/intro/matplotlib/matplotlib.html](https://scipy-lectures.github.io/intro/matplotlib/matplotlib.html) - Similar to the original, but with exercises!\n",
"- [http://cs.smith.edu/dftwiki/index.php/MatPlotLib_Tutorial_1](http://cs.smith.edu/dftwiki/index.php/MatPlotLib_Tutorial_1) - a more concise tour of matplotlib's features, including more detail on different types of plots (histograms, bar charts, etc.).\n",
"- [http://www.labri.fr/perso/nrougier/teaching/matplotlib/](http://www.labri.fr/perso/nrougier/teaching/matplotlib/) - Another good matplotlib tutorial.\n",
"\n",
"## `matplotlib` Documentation\n",
"\n",
"- [http://www.matplotlib.org](http://www.matplotlib.org) - The project web page for matplotlib.\n",
"- [http://matplotlib.org/contents.html](http://matplotlib.org/contents.html) - Main matplotlib documenation page.\n",
"- [https://github.com/matplotlib/matplotlib](https://github.com/matplotlib/matplotlib) - The source code for matplotlib.\n",
"- [http://matplotlib.org/gallery.html](http://matplotlib.org/gallery.html) - A large gallery showcaseing various types of plots matplotlib can create. \n",
"- [http://scipy-lectures.github.io/matplotlib/matplotlib.html](http://scipy-lectures.github.io/matplotlib/matplotlib.html) - Another good matplotlib reference."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.10"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment