Say “Hello!” to the World of Plots
By: Rukshan Pramoditha
Tags: Seaborn, Python, Matplotlib, Data Science, Data Visualization

“A picture is worth a thousand words.” This is often true in the world of Data Science. Data visualization plays a key role as it allows you to reveal the patterns behind the data. There are three primary uses for data visualization:

To explore data

data To validate a model

a model To communicate data

Exploratory Data Analysis (EDA), which uses visualization techniques, allows you to understand different characteristics of data, its variables and the potential relationships between them. We also use statistical visualization techniques to validate a model and its assumptions. Finally, we create eye-pleasing and publication-quality visualizations to communicate the results to our audience.

There are many data visualization libraries in Python. matplotlib and seaborn are mostly used. matplotlib is a basic data visualization library and provides techniques to create and customize plots. seaborn is a high-level data visualization library which provides more advanced techniques to create eye-pleasing and sophisticated plots with less code! Since seaborn was built on top of matplotlib, we often use matplotlib to customize seaborn plots. matplotlib provides fundamentals concepts for both libraries. So, learning both libraries is very important to visualize data effectively.

In the very first tutorial of the data visualization topic, I’ll give more emphasis to matplotlib basics, plot anatomy and workflow of creating plots. I’ll discuss the following topics in detail. You are all welcome to say “Hello” to the world of plots!

Topics discussing

matplotlib APIs: pyplot interface, object-oriented interface

pyplot interface, object-oriented interface pyplot submodule in matplotlib

%matplotlib command: %matplotlib notebook, %matplotlib inline

%matplotlib notebook, %matplotlib inline Controlling the style

Figure, Axes and Axis

Anatomy of a figure

Basic steps for creating a plot

Creating a single plot on the figure

Creating a plot using the pyplot interface

Creating multiple plots on the same figure

Creating a plot using seaborn

Plotting multiple lines in the same plot

Creating box plots

Automating the figure creation process

Reasons for automating

Good practices for using matplotlib and seaborn

Dependencies

Dataset used

A note on the matplotlib APIs

The matplotlib library has two different application programming interfaces (APIs):

The pyplot interface

The object-oriented interface

The pyplot interface is based on MATLAB and contains MATLAB-style tools. It is mainly intended for creating simple plots.

If you need more control and customization of your plots, it is better to use the object-oriented interface of matplotlib. This interface allows you for working directly with objects. The main concept behind using this interface is to create Figure and Axes objects and then just call the methods and attributes of those objects.

Now, there is a question. Which interface (pyplot or object-oriented) should I use? The answer is:

For more simple plots, the choice between the two interfaces is a matter of your preference, but the object-oriented interface should be used when plots become more complicated where you need more control and customization over them.

The pyplot submodule in matplotlib

The matplotlib library includes many submodules. Some of them are:

matplotlib. artist

matplotlib. colors

matplotlib. pyplot

matplotlib.style

We mostly deal with the pyplot submodule which creates plots of data in an object-oriented manner and provides the plotting interface. You should be careful not to confuse the pyplot submodule with the pyplot interface. Those are two different things.

By convention, pyplot in matplotlib is imported under the alias plt as:

Earlier, I discussed two interfaces of matplotlib. In the object-oriented interface, the pyplot submodule is used only for a few tasks such as creating a figure, showing a figure and the rest is done by calling the appropriate methods and attributes of Figure and Axes objects.

The %matplotlib command

Plotting within an IPython notebook (eg. Jupyter notebook) can be done with the %matplotlib command. %matplotlib is a magic function in IPython. There are two ways to use the %matplotlib command within a Jupyter notebook:

%matplotlib notebook : will lead to interactive (zoomable & resizeable) plots embedded within the notebook.

: will lead to interactive (zoomable & resizeable) plots embedded within the notebook. %matplotlib inline: will lead to static images of your plot embedded within the notebook. %matplotlib inline sets the backend of matplotlib to the ‘inline’ backend. With this backend, the output of plotting commands is displayed inline within the Jupyter notebook, directly below the code cell.

Tips for using the %matplotlib command

To embed your figure within the Jupyter notebook, you should run either %matplotlib notebook or %matplotlib inline.

or It is recommended to run the command before importing the matplotlib library to avoid any potential error.

You should not run both commands at once per Python session.

If you are using matplotlib within a Python script (.py file), you don’t need to use any of these commands.

If you want to work interactively with your plots, use the %matplotlib notebook command.

command. If you want static plots directly embedded below the code cell, use the %matplotlib inline command. If you want to change the figure size of a static plot, you have various options to do that.

Controlling the style

In matplotlib

matplotlib includes a number of new stylesheets. You can set a style by running the following command before creating a graph.

Replace style with one of the available styles in matplotlib. You can get a list of available styles by running the following command.

Once you’ve activated a style, it will be used throughout the current session. To go back to the matplotlib default style, run the following command.

In seaborn

seaborn has five built-in themes to style plots: darkgrid, whitegrid, dark, white and ticks. The default theme is darkgrid. To change the theme, pass the name of it to sns.set_style().

Figure, Axes and Axis

The following image shows the main elements of a graph.

Figure: The Figure object is the final image and can be seen as the canvas on which all other elements are plotted. The Figure can contain one or more Axes.

The Figure object is the final image and can be seen as the canvas on which all other elements are plotted. The Figure can contain one or more Axes. Axes: The Axes object represents an individual plot (subplot ). Axes create subdivisions on the Figure. Other objects such as the title, the x-label and the y-label belong to the Axes object.

The Axes object represents an individual plot (subplot ). Axes create subdivisions on the Figure. Other objects such as the title, the x-label and the y-label belong to the Axes object. Axis: Each of the Axes (subplots) consists of one or more Axis; (horizontal) x-axis, (vertical) y-axis and (depth) z-axis. Axis objects represent numerical values for each subplot. They also define the limits and manage the ticks (the mark on the axes) and tick labels (the label text represented on each tick).

The following image shows the anatomy of a figure.

Image copyright: matplotlib.org

Basic steps for creating a plot

The following steps describe the standard workflow that you should follow to create a plot. It is necessary to follow the steps in the given order. But you may skip some steps depending on your needs.

Step 1: Run the %matplotlib inline magic command.

Step 2: Import the matplotlib library and other libraries you want.

Step 3: Set the style to use when creating the plot. Otherwise, matplotlib or seaborn uses its default style.

Step 4: Prepare or get data

Step 5: Create the Figure and the Axes objects

Step 6: Create the plot (bar chart, box plot, histogram, etc.)

Step 7: Customize the plot

Step 8: Save the plot as a file (.png, .jpg, etc.)

Step 9: Show (display) the plot

Now, let me create some plots for you by following the above workflow.

Creating a single plot on the figure

Now, I create a histogram for the carat variable in the diamonds.csv dataset. Here I use the matplotlib.pyplot hist() function to create the histogram. Since I use the object-oriented interface of matplotlib, first I create Figure (fig) and Axes (ax) objects and then just call the methods such as hist(), set_title() of those objects. Note that the subplots() function in matplotlib.pyplot creates the Figure and the Axes objects at the same time.

The output is:

Note 1: Since I specified the dpi to 300 when saving the figure, I can get a high-quality image with the resolution of 1800 x 1200.

Note 2: You need to run the plt.show() command to display the figure. If you’re running Python commands in a Jupyter notebook, you can run this command several times in a single Python session in order to create multiple plots in different code cells. If you’re using Python script (.py file), the plt.show() command should be used only once per Python session and is most often seen at the very end of the script.

Note 3: If you want to both view the image on the screen and save it in a file, remember to run the plt.savefig() command before the plt.show() command to make sure you don’t save a blank canvas!

Creating the above plot using the pyplot interface

Now, I want to show you how to create the above plot using the pyplot interface of matplotlib. This is the only graph that I create using this interface, in this tutorial. I generally prefer to use the object-oriented interface because it gives me more control and customization of the plots.

Note the following changes:

Object-oriented interface → Pyplot interface

hist() method of ax object → hist() function of pyplot submodule

method of object → function of pyplot submodule set_title() method of ax object → title() function of pyplot submodule

method of object → function of pyplot submodule set_xlabel() method of ax object → xlabel() function of pyplot submodule

method of object → function of pyplot submodule set_ylabel() method of ax object → ylabel() function of pyplot submodule

And also:

You don’t need to create the Figure and Axes objects.

Creating multiple plots on the same figure

Earlier, I used the subplots() function without specifying any parameters. When used in this way, it creates one Figure object and one Axes object (subplot). Now, I want to create 4 subplots (4 Axes objects) on the same figure. This time, I use the same subplots() function with nrows and ncols parameters. For example, If I use subplots(nrows=2, ncols=2), this creates one Figure object and 4 Axis (subplots) in a grid of 2 rows and 2 columns. The variable name ax, is no longer only one Axis object. Instead, ax is an array of Axis objects with a shape of 2 x 2. You can check its shape by running the ax.shape command.

Now, I want to create a figure which contains 4 histograms of carat, depth, table, price in the diamonds.csv dataset. To add data:

You first index into ax . You should use two indexes since ax is a two-dimensional array.

. You should use two indexes since is a two-dimensional array. Then you call the hist() method on each element (subplot/axes) in the array.

method on each element (subplot/axes) in the array. If you want to customize each plot, you can call appropriate methods such as set_title(), set_xlabel() on each element (subplot/axes) in the array.

The output is: