Creating Side-by-Side Subplots in Jupyter Notebook: Integrating Matplotlib subplots with Pandas

Dec 04, 2025 · Programming · 8 views · 7.8

Keywords: Jupyter Notebook | Matplotlib subplots | Pandas plotting

Abstract: This article explores methods for creating multiple side-by-side charts in a single Jupyter Notebook cell, focusing on solutions using Matplotlib's subplots function combined with Pandas plotting capabilities. Through detailed code examples, it explains how to initialize subplots, assign axes, and customize layouts, while comparing limitations of alternative approaches like multiple show() calls. Topics cover core concepts such as figure objects, axis management, and inline visualization, aiming to help users efficiently organize related data visualizations.

Introduction

In data analysis and scientific computing, Jupyter Notebook (originally IPython Notebook) is widely favored for its interactivity and visualization capabilities. Users often need to display multiple related charts in a single cell to enhance logical coherence, rather than scattering them across different cells. Based on a common query—how to draw independent charts side-by-side in a Notebook instead of overlaying them on the same chart—this article delves into best practices, particularly leveraging the integration of Matplotlib's subplots function with Pandas plotting features.

Problem Context and Common Pitfalls

By default, when using Pandas' plot() method in Jupyter Notebook, executing commands like df['korisnika'].plot() and df['osiguranika'].plot() plots both on the same chart, causing line overlap. This is suitable for trend comparison but insufficient when independent display is required. A simple workaround is to plot in separate cells, but this disrupts the unity of logical units. Another approach involves multiple calls to plt.show(), for example:

plt.plot(a)
plt.show()
plt.plot(b)
plt.show()

While this generates multiple charts, they are stacked vertically in the output, not arranged side-by-side, and may impact performance due to frequent rendering. Thus, a better solution is needed to achieve horizontal layout.

Core Solution: Using Matplotlib subplots

The optimal method is to use Matplotlib's subplots function to pre-create multiple axes and pass them to Pandas plotting functions. This allows managing multiple subplots within a single figure object, enabling side-by-side display. The following code example illustrates this process:

import matplotlib.pyplot as plt
import pandas as pd

# Assuming df is a Pandas DataFrame with columns 'korisnika' and 'osiguranika'
fig, axs = plt.subplots(1, 2)  # Create a subplot layout of 1 row and 2 columns
df['korisnika'].plot(ax=axs[0])  # Plot on the first subplot
df['osiguranika'].plot(ax=axs[1])  # Plot on the second subplot
plt.tight_layout()  # Automatically adjust subplot parameters to avoid overlap
plt.show()

In this code, plt.subplots(1, 2) returns a figure object fig and an array axs containing two axes. By specifying the ax parameter, Pandas' plot() method draws data onto specific axes instead of the default current axis. This ensures each chart is independent and arranged side-by-side. Using plt.tight_layout() optimizes subplot spacing for better readability.

In-Depth Analysis and Extended Applications

The core of this method lies in axis management. In Matplotlib, the figure object (Figure) is the top-level container, while axes (Axes) represent individual chart areas. Through subplots, we can flexibly define grid layouts, e.g., plt.subplots(2, 2) creates a 2x2 subplot array. For Pandas integration, this is seamless as Pandas plotting methods are essentially wrappers around Matplotlib.

Furthermore, users can customize subplot properties, such as adding titles, adjusting sizes, or modifying colors. For example:

fig, axs = plt.subplots(1, 2, figsize=(10, 4))  # Set figure size
axs[0].set_title('Korisnika Data')
axs[1].set_title('Osiguranika Data')
df['korisnika'].plot(ax=axs[0], color='blue')
df['osiguranika'].plot(ax=axs[1], color='green')
plt.show()

Compared to other methods like multiple show() calls, this solution is more efficient as it reduces rendering overhead and offers better layout control. In Jupyter Notebook, combined with the %matplotlib inline magic command, charts are embedded directly for easy interaction and sharing.

Conclusion

Creating side-by-side charts in Jupyter Notebook is a key technique for enhancing data visualization. By using Matplotlib's subplots function with Pandas plotting capabilities, users can easily manage multiple independent charts and achieve horizontal layouts. This approach not only addresses the issue of chart overlap in the original problem but also provides extensibility and customization options. It is recommended to adjust parameters based on specific needs in practice to optimize visual output. For more complex scenarios, further exploration of Matplotlib's layout tools or advanced libraries like Seaborn is encouraged.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.