How to adjust Matplotlib plot to fit its elements


I created a plot using Matplotlib, it looked fine. I then rotated the X-axis tick labels to vertical rotation. In the rendered plot the label texts were cropped off.


Plots in Matplotlib used to be difficult to scale to fits its elements. But now there is a simple call to scale it to fit its elements: tight_layout

import matplotlib.pyplot as mplot
# Add stuff to the plot
# Render or save the plot

Tried with: Ubuntu 14.04

Cannot import name _tkagg


I had Matplotlib installed on a computer. I tried to set the backend for a plot using TkAgg. There was no Tk installed, so I installed the required packages. When I tried to set backend again, I got this error: ImportError: cannot import name _tkagg


Check if your Matplotlib is installed using pip. If so, then you need to reinstall Matplotlib so that it picks up links to the python-tk files correctly:

$ sudo pip uninstall matplotlib
$ sudo pip install matplotlib

The plot was displayed correctly after this.

Tried with: Ubuntu 14.04

Matplotlib plot is not displayed in window


I created a plot using the Matplotlib library in a Python script. But the call to show does not display the plot in a GUI window.


The rendering of a plot to a file or display is controlled by the backend that is set in Matplotlib. You can check the current backend using:

import matplotlib

I got the default backend as Agg. The possible values for GUI backends on Linux are Qt4Agg, GTKAgg, WXagg, TKAgg and GTK3Agg. Since Agg is not a GUI backend, nothing is being displayed.

I wanted to use the simple Tcl-Tk backend. So, I installed the necessary packages for Python:

$ sudo apt install tcl-dev tk-dev python-tk python3-tk

The backend is not set automatically after this. In my Python script, I set it explicitly:

import matplotlib
matplotlib.rcParams["backend"] = "TkAgg"

The plot was displayed after this change.

However, this needs to be set immediately after the import line of Matplotlib and before importing matplotlib.pyplot. Doing this in the import region of a Python script is quite ugly.

Instead, I like to switch the backend of the matplotlib.pyplot object itself:

import matplotlib.pyplot as mplot

This too worked fine for me! 🙂

Reference: Matplotlib figures not showing up or displaying

Tried with: Ubuntu 14.04

How to remove padding around plot in Matplotlib

The plot generated by Matplotlib typically has a lot of padding around it. This is useful if you are viewing or displaying the plot in isolation. However, when the plot is embedded inside another document, typically extra padding is added around and makes the plot look tiny. The solution is to reduce or remove the padding around the plot generated by Matplotlib.

This can be done by configuring the bounding box used for the plot while saving it to disk:

import matplotlib.pyplot as mplot
mplot.savefig("foo.pdf", bbox_inches="tight")

This makes the bounding box tight around the plot, while still giving enough space for the text or lines on the plot periphery.

If you want a plot with zero padding around it:

import matplotlib.pyplot as mplot
mplot.savefig("foo.pdf", bbox_inches="tight", pad_inches=0)

Personally, I find this too tight, but it might be useful in some situations.

Tried with: Matplotlib 1.4.3, Python 2.7.3 and Ubuntu 14.04

How to customize Matplotlib using matplotlibrc

If you find yourself using Matplotlib a lot, then it might be worth your while to customize its default configuration. This is best done using a matplotlibrc file.

  • You can find the global configuration file at /etc/matplotlibrc.

  • If you installed Matplotlib using pip, there is another global configuration file inside your Python installation that overrides the one in /etc. On my system, this path was /usr/local/lib/python2.7/dist-packages/matplotlib/mpl-data/matplotlibrc.

  • The best way to keep your Matplotlib customizations is to maintain it in your home directory at: ~/.config/matplotlib/matplotlibrc. You can have a look at the default configurations in the global files (above) and only set those you want to change in your home file.

Matplotlib will pick up these settings whenever it is executed.

Tried with: Matplotlib 1.4.3, Python 2.7.6 and Ubuntu 14.04

How to draw scatter plot using Matplotlib

Scatter plot drawn using Matplotlib
Scatter plot drawn using Matplotlib

Scatter plots are useful to show data points that lie in 2D. Drawing a scatter plot in Matplotlib is easy using the scatter function.

  • Assuming your data points are available as two NumPy arrays of shape (N, 1), drawing a scatter plot is straightforward:
import matplotlib.pyplot as mplot

# x_vals is NumPy array of shape (N, 1)
# y_vals is NumPy array of shape (N, 1)
mplot.scatter(x_vals, y_vals)
  • By default, markers that are filled discs, that is of type o, are drawn. This can changed to any of the other markers available in Matplotlib using the marker input argument. The different markers of Matplotlib are shown here.

  • The size of the marker is 20 by default. It can be changed by setting the s input argument.

  • The edge or border of the markers are drawn in black by default. If you do not want the edges to be drawn, then set the edgecolors input argument to none (a string, not the None value).

  • The color that is filled inside the marker is called the face color. It can be set by using the facecolors input argument. For setting the RGB values of N points, pass a NumPy array of shape (N, 3) where each color value lies in (0, 1).

  • If a dense set of data points is being drawn, multiple markers could obscure each other. This situation can be improved by adding some transparency to the markers. This can be set using the alpha input argument.

  • An example that uses all the above customizations to draw the figure shown above:

import matplotlib.pyplot as mplot

# x_vals is NumPy array of shape (N, 1)
# y_vals is NumPy array of shape (N, 1)
# c_arr  is NumPy array of shape (N, 3)

mplot.scatter(x_vals, y_vals, s=2, marker=".", facecolors=c_arr, edgecolors="none", alpha=0.5)

Tried with: Matplotlib 1.3.1 and Ubuntu 14.04

How to use LaTeX for text rendering in Matplotlib

By default, Matplotlib does not use LaTeX to render the text in its plots. For certain documents, it may be necessary to use LaTeX for text rendering.

Matplotlib can be requested to use LaTeX using:

from matplotlib import rc
rc('text', usetex=True)

Tried with: Matplotlib 1.3.1 and Ubuntu 14.04

How to install Seaborn

Left: Matplotlib Right: Seaborn
Left: Matplotlib Right: Seaborn

Seaborn is a plotting library that is built on top of Matplotlib. For folks already using Matplotlib, it makes it easy to generate visually pleasing plots that use contemporary colors and features. The key selling point is that you can do this by making zero or very few additions to your Matplotlib code! 🙂

To install Seaborn:

$ sudo apt install python-scipy python-pandas
$ sudo pip install seaborn

It takes just a single line of code for Seaborn to change your plots:

import seaborn

With just this line, it changes the fonts, layout and colors used resulting in a much more pleasing plot. If you want to go further, you can use Seaborn to use beautiful color palettes and other features described in their tutorial.

Tried with: Seaborn 0.5.1, Matplotlib 1.3.1, Python 2.7.6 and Ubuntu 14.04