In this article, we will learn how to add markers to a Graph Plot using Matplotlib with Python. For that one must be familiar with the following concepts:
Matplotlib: Matplotlib may be a multi-platform data visualization library built on NumPy arrays designed to figure with the broader SciPy stack. Matplotlib Subplots: The matplotlib.pyplot.subplots() method provides a way to plot multiple plots on a single figure. Given the number of rows and columns, it returns a tuple (fig, ax), giving a single figure fig with an array of axes ax.Add Subplots in MatplotlibHere we are demonstrating different examples of how to Create Subplots in Matplotlib with Python using plt.subplots:
Creating Multiple Subplots using plt.subplotsCreating Multiple Subplots of Line PlotsCreating Multiple Subplots of Bar PlotsCreating Multiple Subplots of Pie ChartsCreating a custom Multiple SubplotsCreating Multiple Subplots using plt.subplotsThe code is a simple example of how to create a Matplotlib subplot figure. Create a matplotlib subplot with a 3×3 grid of subplots, and iterate over the subplots to plot a random line in each subplot.
Python3# importing packagesimport matplotlib.pyplot as pltimport numpy as np # making subplots objectsfig, ax = plt.subplots(3, 3) # draw graphfor i in ax: for j in i: j.plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5)) plt.show()Output :
Example: Create a matplotlib subplot with a 2×2 grid of subplots, plot the sine, cosine, tangent, and sinc functions in different subplots with different line styles and colors, and display the figure
Python3# importing packagesimport matplotlib.pyplot as pltimport numpy as np # making subplots objectsfig, ax = plt.subplots(2, 2) # create datax = np.linspace(0, 10, 1000) # draw graphax[0, 0].plot(x, np.sin(x), 'r-.')ax[0, 1].plot(x, np.cos(x), 'g--')ax[1, 0].plot(x, np.tan(x), 'y-')ax[1, 1].plot(x, np.sinc(x), 'c.-') plt.show()Output :
In this example, code generates three different mathematical functions (sine, cosine, and tangent) and plots them using subplots in Matplotlib.
Python3import matplotlib.pyplot as pltimport numpy as np # Generate random data for subplotsx = np.linspace(0, 10, 100)y1 = np.sin(x)y2 = np.cos(x)y3 = np.tan(x) # Create subplots with line plotsfig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4)) axes[0].plot(x, y1, color='blue', label='sin(x)')axes[1].plot(x, y2, color='green', label='cos(x)')axes[2].plot(x, y3, color='orange', label='tan(x)') # Add titles and legendsaxes[0].set_title('Sine Function')axes[1].set_title('Cosine Function')axes[2].set_title('Tangent Function') for ax in axes: ax.legend() # Adjust layout for better spacingplt.tight_layout() # Display the figureplt.show()Output:

In this example, first we will creates a DataFrame with random categorical data and generates three bar charts to visualize the distribution of each data category using subplots in Matplotlib.
Python3import matplotlib.pyplot as pltimport pandas as pd # Create a DataFrame with random categorical datadata = {'Category': ['A', 'B', 'C', 'D'], 'Value1': np.random.randint(1, 10, 4), 'Value2': np.random.randint(1, 10, 4), 'Value3': np.random.randint(1, 10, 4)} df = pd.DataFrame(data) # Create subplots with bar plotsfig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4)) df.plot(kind='bar', x='Category', y='Value1', color='skyblue', ax=axes[0])df.plot(kind='bar', x='Category', y='Value2', color='lightgreen', ax=axes[1])df.plot(kind='bar', x='Category', y='Value3', color='coral', ax=axes[2]) # Add titlesaxes[0].set_title('Value1 Distribution')axes[1].set_title('Value2 Distribution')axes[2].set_title('Value3 Distribution') # Adjust layout for better spacingplt.tight_layout() # Display the figureplt.show()Output:

In this example, it generates random data for three pie charts and creates subplots to display them using subplots in Matplotlib.
Python3import matplotlib.pyplot as plt # Generate random data for subplotslabels = ['Category 1', 'Category 2', 'Category 3']sizes1 = np.random.randint(1, 10, 3)sizes2 = np.random.randint(1, 10, 3)sizes3 = np.random.randint(1, 10, 3) # Create subplots with pie chartsfig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4)) axes[0].pie(sizes1, labels=labels, autopct='%1.1f%%', colors=['lightcoral', 'lightblue', 'lightgreen'])axes[1].pie(sizes2, labels=labels, autopct='%1.1f%%', colors=['gold', 'lightseagreen', 'lightpink'])axes[2].pie(sizes3, labels=labels, autopct='%1.1f%%', colors=['lightskyblue', 'lightgreen', 'lightcoral']) # Add titlesaxes[0].set_title('Pie Chart 1')axes[1].set_title('Pie Chart 2')axes[2].set_title('Pie Chart 3') # Adjust layout for better spacingplt.tight_layout() # Display the figureplt.show()Output:

In this example, we will see how to create a custom subplot layout using GridSpec in Matplotlib. It creates a figure with four subplots arranged in a non-standard grid and displays different types of visualizationscode like line plots, scatter plots, bar plots, and pie charts in separate subplots using Matplotlib.
Python3import matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport numpy as np # Creating a custom layout with different subplot sizesfig = plt.figure(figsize=(12, 6)) # Using gridspec to define the layoutgs = gridspec.GridSpec(2, 3, width_ratios=[1, 2, 1], height_ratios=[2, 1]) # Creating subplots based on the layoutax1 = plt.subplot(gs[0, 0])ax2 = plt.subplot(gs[0, 1])ax3 = plt.subplot(gs[0, 2])ax4 = plt.subplot(gs[1, :]) # Customizing each subplot with different visualizations # Subplot 1: Line Plotx = np.linspace(0, 10, 100)y1 = np.sin(x)ax1.plot(x, y1, color='blue')ax1.set_title('Line Plot - Sine Function') # Subplot 2: Scatter Plotx = np.random.rand(30)y2 = 3 * x + np.random.randn(30)ax2.scatter(x, y2, color='green')ax2.set_title('Scatter Plot') # Subplot 3: Bar Plotcategories = ['A', 'B', 'C', 'D']values = np.random.randint(1, 10, 4)ax3.bar(categories, values, color='orange')ax3.set_title('Bar Plot') # Subplot 4: Pie Chartlabels = ['Category 1', 'Category 2', 'Category 3']sizes = np.random.randint(1, 10, 3)ax4.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['lightcoral', 'lightblue', 'lightgreen'])ax4.set_title('Pie Chart') # Adjusting layout for better spacingplt.tight_layout() # Displaying the figureplt.show()Output:

D
deepanshu_rustagiImprove Next ArticleHow to Generate Subplots With Python's Matplotlib Please Login to comment...