How to fix height of colorbar in Matplotlib

When a colorbar is used in a Matplotlib plot, it is usually drawn with a height that is larger than the plot itself. Many solutions to this problem are suggested here. The one that worked for me was this:

plt.colorbar(im, fraction=0.046, pad=0.04)

This sets the colorbar height equal to the height of the plot for me.

Tried with: Matplotlib 1.3.1-1, Python 2.7.6 and Ubuntu 14.04

How to get orthographic projection in 3D plot of Matplotlib


The 3D plots generated by Matplotlib are rendered from a perspective projection. Due to this, the Z axis is not vertical when rendered from certain rotation angles or elevations. Matplotlib was designed inspired from the Matlab plotting API. In contrast, in Matlab it is pretty easy to get orthographic projection in 3D plots where the Z axis is perfectly vertical.


Orthographic projection is currently not supported in Matplotlib. A pull request with code has been given for it as seen here. We can adapt that code in our Python scripts to get a vertical Z axis. Just use this code snippet:

import numpy
from mpl_toolkits.mplot3d import proj3d

def orthogonal_proj(zfront, zback):
    a = (zfront+zback)/(zfront-zback)
    b = -2*(zfront*zback)/(zfront-zback)
    # -0.0001 added for numerical stability as suggested in:
    return numpy.array([[1,0,0,0],

# Later in your plotting code ...
proj3d.persp_transformation = orthogonal_proj

As you can notice, we add -0.0001 as a small perturbation from 0 to give the code numerical stability, as suggested here. Without this, the Z axis could be generated as inverted or at the wrong end of the plot. By adding the above code, I was able to get orthographic project for my 3D plots with perfectly vertical Z axis.

Tried with: Matplotlib 1.3.1, Python 2.7.6 and Ubuntu 14.04

How to create a confusion matrix plot using Matplotlib

Confusion matrix plot generated using Matplotlib
Confusion matrix plot generated using Matplotlib

Confusion matrix is an excellent method to illustrate the results of multi-class classification. It takes a single function call in Matplotlib to generate a colorful confusion matrix plot. However, you have to first have your results in the form of a confusion matrix.

Let me illustrate with an example. Assume, you have 4 classes: A, B, C and D. Your classifier does great on A, C and D with fully accurate results. However, for results that should be class B, it classifies them as A 10% of the time and as C 20% of the time. You should be able to extract such classification results from your classifier easily.

You just need to put these results in a 2D float Numpy array in the form of a confusion matrix. In this type of matrix, typically the true classes are listed on the Y axis, top to bottom. The predicted classes are listed on X axis, from left to right. For our example, the confusion matrix would look like this:

[[100 0  0   0  ]
 [10  70 20  0  ]
 [0   0  100 0  ]
 [0   0  0   100]]

Optionally, you can also normalize the results to 1.0:

[[1.0 0   0   0  ]
 [0.1 0.7 0.2 0  ]
 [0   0   1.0 0  ]
 [0   0   0   1.0]]

Once you have this as a 2D float Numpy array, just pass it to the matshow method of Matplotlib to generate the confusion matrix plot. To get a temperature scale of the colors used in the plot, call the colorbar method:

import matplotlib.pyplot as plt

# Assume m is 2D Numpy array with these values
# [[1.0 0   0   0  ]
#  [0.1 0.7 0.2 0  ]
#  [0   0   1.0 0  ]
#  [0   0   0   1.0]]


To add X-axis, Y-axis labels, and other modifications, use the typical calls you use in Matplotlib for other types of plots.

Tried with: Python 2.7.6 and Ubuntu 14.04

Colors in Matplotlib

Named colors can be specified by using a single character enclosed in quotes. For example, line_color = "r".

The named colors are:

b: blue
g: green
r: red
c: cyan
m: magenta
y: yellow
k: black
w: white

Other named colors can be seen illustrated here.

A RGB color can be specified in hexadecimal format as line_color = "#eeefff"


How to add math to Matplotlib plot

Sometimes, you may need to add LaTeX mathematical expressions to a Matplotlib plot. For example, adding Greek symbols, superscript, subscript or formulas to the axis labels, plot title or tick labels.

Doing that is very easy in Matplotlib. Just indicate the text to be a raw string and enclose the mathematical expression in dollar signs. For example:

import matplotlib.pyplot as mplot
mplot.xlabel(r"$x_1 > x_3$")

Tried with: Python 2.7.6 and Ubuntu 14.04

How to use PrettyPlotLib

A common method to generate plots in Python is to use the matplotlib module. While functional, these plots are not very beautiful to look at. PrettyPlotLib aims to fix this by generating beautiful plots with only small modifications to the code that is already using matplotlib.

I prefer to install this module and its dependencies using Pip:

$ sudo pip install brewer2mpl
$ sudo pip install prettyplotlib

To use this module, change the plot and legend functions in your code to use the prettyplotlib module instead of matplotlib.pyplot.

For example:

# Old code
import matplotlib.pyplot as mplot

mplot.legend(loc="best", numpoints=1)

# New code
import matplotlib.pyplot as mplot
import prettyplotlib as pplot

pplot.legend(loc="best", numpoints=1)

Note: PrettyPlotLib is not being actively developed anymore. Its creator recommends using the Seaborn module with Matplotlib instead.

Tried with: PrettyPlotLib 0.1.7, Python 2.7.6 and Ubuntu 14.04

Markers of Matplotlib

Markers in Matplotlib
Markers in Matplotlib

Markers are used in Matplotlib plots to mark the points on a line which refers to a datapoint. All the possible marker styles in Matplotlib are listed here.

However, it is difficult to pick a marker just by looking at its character or its label. I generated the above image as a visual reference to pick markers. It was generated by using this piece of code:

Tried with: Matplotlib 1.3.0 and Ubuntu 12.04 LTS

How to create a pie chart using Matplotlib

Pie chart created with Matplotlib
Pie chart created with Matplotlib

Creating a pie chart is easy using Matplotlib. A simple pie chart can be created by passing the values representing each of the slices of the pie to the matplotlib.pyplot.pie method. For example:

Typically, you want some additions to the simple pie chart:

1. The pie chart is oval by default. To make it a circle, call matplotlib.pyplot.axis("equal")

2. To show labels of each pie slice, pass them as a list of strings to the labels parameter of the matplotlib.pyplot.pie method.

3. To show the percentage of each pie slice, pass an output format to the autopct parameter of the matplotlib.pyplot.pie method.

4. To display a title for the pie chart, call the matplotlib.pyplot.title method.

The pie chart shown above was created by these simple additions. The code is below:

Tried with: Matplotlib 1.3.0 and Ubuntu 12.04 LTS