06 August 2015

Publication ready figures with matplotlib and Jupyter notebook

A very convenient workflow to analyze data interactively in Python is to use the Jupyer notebook or IPython Notebook in combination with matplotlib. These figures can be used in various ways and file formats depending on the kind of publication.
For instance, to put the figure on a webpage, most softwares support only png or jpg formats, so that a fixed resolution must be provided. On the other hand, a scalable figure format can be scaled as needed and readily used in a pdf document, such as a pgf image in a journal that uses LaTeX. This way, there won't be artifacts when zooming into the figure. This blog post contains a small function that saves the matplotlib figure to various file formats automatically, which can then be used for various occasions.

Creating a simple plot

A simple sample plot can be created within an jupyter notebook with:
  • Loading matplotlib and setting up jupyter notebook to display the graphics inline:
In [1]:
%matplotlib inline
import seaborn as snb
import numpy as np
import matplotlib.pyplot as plt
  • Creating a quatratic plot:
In [2]:
def create_plot():
    x = np.arange(0.0, 10.0, 0.1)
    plt.plot(x, x**2)
    plt.xlabel("$x$")
    plt.ylabel("$y=x^2$")
    
create_plot()
plt.show()

Save the figure

The previous figure can be saved with calling savefig from matplotlib.pyplot and matplotlib will save the figure in the output format based on the extension of the filename. To save to various formats, one would need to call this function several times or instead define a new function that can be included as boilerplate in the first cell of a notebook such as:
In [3]:
def save_to_file(filename, fig=None):
    """Save to @filename with a custom set of file formats.
    
    By default, this function takes to most recent figure,
    but a @fig can also be passed to this function as an argument.
    """
    formats = [
                "pdf",
                "eps",
                "png",
                "pgf",
              ]
    if fig is None:
        for form in formats:
            plt.savefig("%s.%s"%(filename, form))
    else:
        for form in formats:
            fig.savefig("%s.%s"%(filename, form))
And it can be easily saved with:
In [4]:
create_plot()
save_to_file("simple_plot")
My choice of formats is to save in the png format to put this figure online such as on a web page and several scalable figure formats to include it in a pdf. I will write more on how to do that with LaTeX in a future blog post.
The full notebook for creating the figure above and with the boilerplate in the first cell of the notebook can be found at github.


Edited:

  • August 09, 2017: Use jupyter instead ipython in the text.
 

1 comment:

  1. Thanks for sharing the descriptive information on Python tutorial. It’s really helpful to me since I'm taking Python training. Keep doing the good work and if you are interested to know more on Python, do check this Python tutorial.:-https://www.youtube.com/watch?v=HcsvDObzW2U

    ReplyDelete