Open In App

25+ Most Used Matplotlib Snippets in 2025

Last Updated : 22 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Matplotlib is the most popular open-source Python library applied for creating, interactive as well as animated and static visualizations. Matplotlib is one of the oldest and very versatile libraries for data visualization in Python. A wide variety of plot tools are provided by Matplotlib for users to create graphs, charts, and plots with a high degree of customization.

25-Most-Used-Matplotlib-Snippets

In this article we will discuss the use of matplotlib snippets in Python;

What is Matplotlib ?

Matplotlib is a comprehensive and powerful Python library used to generate visualizations that can range from very simple to very highly customized plots. It allows generating a wide range of different charts from simple line plots to scatter plots, bar charts, histograms, pie charts and many more. Therefore, it is necessary for data analysis and presentation.

Matplotlib lets every user style all dimensions of a plot: colors and labels, style and axes. It works well with libraries such as NumPy and Pandas, easy to view structures as plots. Also, Matplotlib supports export in formats like PNG, PDF and SVG that allow plots to be used both for interactive applications and publication.

25+ Most Used Matplotlib Snippets in 2025

Here are some of the most commonly used Matplotlib snippets for creating various types of plots and visualizations:

Installation

To install Matplotlib, you will use Python's package manager pip or if you are working in an environment that uses Anaconda, you might have conda.

Installing via pip

1. Verify Python Install:

First make sure Python is installed. Open your terminal or command prompt and run the following:

Python
python --version

If Python is not installed, download it from the [official Python website] (https://www.python.org/downloads/)

2.Install Matplotlib:

Now that you've confirmed Python is installed, you can install Matplotlib with pip. Here's what you need to do:

Python
pip install matplotlib

3. Test Installation

You can run a simple script to verify whether Matplotlib is installed correctly. Open a new Python file and paste the following code in it:

Python
import matplotlib
print(matplotlib.__version__)

Installation with conda

Alternatively, if you have Anaconda or Miniconda installed, you can install Matplotlib using conda

4. Create a New Environment:

Good practice is to create a new environment for your projects

Python
conda create -n my-env python=3.8      # Replace 'my-env' with your environment name
conda activate my-env

5. Install Matplotlib

Use the command below to install

Python
conda install matplotlib

6. Installation Success

Like pip, you can install by running

Python
import matplotlib
print(matplotlib.__version__)

Different types of Plots

Matplotlib has a number of plots for effectively visualizing data. Below are some of the most common ones along with examples:

7. Line Plots

A line plot is one of the most common data visualization types that basically depicts how two variables are correlated by drawing a line connecting data points. In Python, one of the most common libraries for creating a line plot would be Matplotlib because of its utility and versatility.

Python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Basic Line Plot')
plt.show()

Output

file

8. Bar Plot

A bar plot is a very basic form of data visualization that represents categorical data for comparison. Python's Matplotlib library offers a convenient method of drawing a bar chart by utilizing the bar() function of the pyplot module.

Python
categories = ['A', 'B', 'C']
values = [3, 7, 5]
plt.bar(categories, values)
plt.title('Bar Chart')
plt.show()

Output

2

9. Histograms

Histograms are essential for visualization of data where numerical data is represented by forming groups or bins of values and then by illustrating the count of data points falling under each bin. Python offers this at its fingertips via Matplotlib's pyplot by providing a simple way to create histograms with the function pyplot.hist().

Python
import numpy as np

data = np.random.randn(1000)
plt.hist(data, bins=30)
plt.title('Histogram')
plt.show()

Output

3

10. Scatter Plots

Scatter plots are a type of graph used to visualize how one numerical variable could impact another. It can be seen that how one variable changes impacts another. Python's Matplotlib library has a simple means of drawing scatter plots using the command pyplot.scatter().

Python
plt.scatter(x, y)
plt.title('Scatter Plot')
plt.show()

Output

4

11. Pie Charts

Pie charts are one of the most common methods to represent the proportion of various categories in a dataset. Data is represented as slices of a circle where the size of each slice is proportional to its value. Python's Matplotlib library has an easy-to-use function plt.pie() for creating pie charts.

Python
import matplotlib.pyplot as plt

labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)  # Equal aspect ratio ensures that pie is drawn as a circle.
plt.axis('equal')
plt.title('Pie Chart')
plt.show()

Output

5

Customizing Plots

Customizing plots in Matplotlib is crucial for creating visually effective informative visualizations. Matplotlib provides a lot of options to adjust various aspects of your plot such as color, line style, axes properties, annotations, etc. and aesthetics in general. Here's a detailed overview on how to customize your plots properly.

12. Titles and Labels

Titles and labels in plots can be added to draw out the clarity and interpretability of your visualizations using Matplotlib.

Python
plt.plot(x, y)
plt.title("Customized Title", fontsize=16, color='blue', loc='center')  # loc: 'left', 'right', or 'center'
plt.xlabel("Custom X-axis Label", fontsize=12, color='green')
plt.ylabel("Custom Y-axis Label", fontsize=12, color='red')
plt.show()

Output

6

13. Legends

Legends in Matplotlib are important for identifying which data series are shown in a plot. In this regard, legends help viewers to understand what each line, bar or point represents. Adding a legend to your visualizations is possible with the function legend().

Python
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y1 = [10, 20, 25, 30]
y2 = [15, 25, 20, 35]
plt.plot(x, y1, label='Dataset 1', color='blue')
plt.plot(x, y2, label='Dataset 2', color='orange')
plt.title('Customized Legend')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Customizing legend
plt.legend(loc='upper left', ncol=1, facecolor='lightgray', fontsize='medium')
plt.show()
7

14. Gridlines

Gridlines in Matplotlib are always necessary to enhance a plot's legibility by furnishing a base framework of referencing data points. The grid() function is then used to prepare and style those gridlines present in your graphics.

Python
import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title('Customized Gridlines')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Customizing gridlines
plt.grid(color='blue', linestyle='-.', linewidth=1.5, alpha=0.7)
plt.show()
8

15. Colors and Styles

Matplotlib is highly customizable to the colors and styles of the plots, thereby enabling users to create visually informative plots. This section gives a general overview on how to use color and style for effective plots with Matplotlib.

Python
import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4]
y1 = [10, 20, 25, 30]
y2 = [15, 25, 20, 35]
# Customizing first line with solid style and red color
plt.plot(x, y1, label='Dataset A', color='red', linestyle='-', linewidth=2)

# Customizing second line with dashed style and blue color
plt.plot(x, y2, label='Dataset B', color='blue', linestyle='--', marker='o', markersize=8)

# Adding title and labels
plt.title('Customized Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Adding legend
plt.legend()

# Show the plot
plt.show()
9

Subplots and Axes

Subplots and axes are the really powerful features in Matplotlib: they allow to place multiple plots inside a single figure. Those are especially good for comparing data or showing lots of different visualizations in a concise format.

16. Creating Subplots

In a subplot in Matplotlib, one can add as many plots within a figure by making use of subplots so that easy comparisons may be done of multiple datasets or a visual relationship among different complex data may be viewed.

Python
import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
y2 = np.array([10, 20, 30, 40])

# First plot (1 row and 2 columns)
plt.subplot(1, 2, 1)
plt.plot(x, y1)
plt.title('Plot 1')

# Second plot (1 row and 2 columns)
plt.subplot(1, 2, 2)
plt.plot(x, y2)
plt.title('Plot 2')

plt.show()
10

17. Adjusting Axes Limits

This will help to focus on regions of your data. Adjusting axes limits with Matplotlib allows you to be very specific and to highlight different parts of your data. With it, you can set both x-axis limits and y-axis limits in numerous ways.

Python
import matplotlib.pyplot as plt
import numpy as np

# Sample data: Sine wave
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)

# Setting custom limits for x and y axes
plt.xlim(0, 10)     # X-axis range from 0 to 10
plt.ylim(-1.5, 1.5) # Y-axis range from -1.5 to 1.5

# Adding titles and labels
plt.title('Sine Wave')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Show gridlines for better readability
plt.grid(True)

# Display the plot
plt.show()
11

18. Sharing Axes

Sharing axes in Matplotlib is especially useful for subplots that have the same range in their datasets so that by visual comparison, the two datasets appear similar. The share x and share y parameters can be used to make this happen.

a. Basic Sharing

With the sharex or sharey argument set to True, you may share the x or y axis with subplots, respectively. One can also allow sharing by column or row via 'col' or 'row'.

Python
import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create a 2x1 grid of subplots sharing the x-axis
fig, axs = plt.subplots(nrows=2, ncols=1, sharex=True)

axs[0].plot(x, y1, color='blue')
axs[0].set_title('Sine Function')

axs[1].plot(x, y2, color='orange')
axs[1].set_title('Cosine Function')

# Adding labels
for ax in axs:
    ax.set_ylabel('Value')

plt.xlabel('X-axis (shared)')
plt.tight_layout()
plt.show()
12

b. Sharing by Row or Column

Python
# Create a 2x2 grid of subplots sharing x-axis by column and y-axis by row
fig, axs = plt.subplots(nrows=2, ncols=2, sharex='col', sharey='row')

axs[0, 0].plot(x, y1)
axs[0, 0].set_title('Sine Function')

axs[0, 1].plot(x, y2)
axs[0, 1].set_title('Cosine Function')

axs[1, 0].plot(x, y1**2)
axs[1, 0].set_title('Sine Squared Function')

axs[1, 1].plot(x, y2**2)
axs[1, 1].set_title('Cosine Squared Function')

plt.tight_layout()
plt.show()
13

c. Sharing Axes after Creation

When you need to share axes, which is discouraged, but allowed after creating the subplots you could use Axes. Share x() and Axes.share y().

Python
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot(x, y1)
ax2.plot(x, y2)

# Share x-axis after creation
ax2.sharex(ax1)

plt.show()

Working with Tables

Matplotlib also allows one to create tables inside their plot so that he or she is able to visualize better data and graphics. Working with tables in Matplotlib-Includes creating a table, table manipulation, and how to draw them.

19. Creating Tables using 'matplotlib. pyplot. tables()'

You can directly add a table in your plot using the table() function. You can set the cell contents, colors, and many other properties.

Python
import matplotlib.pyplot as plt

data = [
    ['Year', 'Sales', 'Profit'],
    [2021, 15000, 3000],
    [2022, 20000, 5000],
    [2023, 25000, 7000]
]

fig, ax = plt.subplots()
ax.axis('tight')
ax.axis('off')

# Create the table with row and column labels
table = ax.table(cellText=data,
                 colLabels=['Year', 'Sales', 'Profit'],
                 loc='center',
                 cellLoc='center',
                 rowColours=['lightgrey']*4)

plt.title("Customized Sales Data Table")
plt.show()
15

20. Creating tables using Pandas

If you work with data within a Pandas DataFrame then it is relatively simple to convert the same into a Matplotlib table by using pandas.plotting.table() method. The method helps you to display DataFrame contents as visualizations.

NOTE: At the time of compiling this code you should have to install the pandas notebook i.e. "pip install pandas notebook" using command prompt.

Python
import pandas as pd
import matplotlib.pyplot as plt

# Sample DataFrame
data = {
    'Year': [2021, 2022, 2023],
    'Sales': [15000, 20000, 25000],
    'Profit': [3000, 5000, 7000]
}
df = pd.DataFrame(data)

# Create a figure and axis
fig, ax = plt.subplots()

# Hide axes
ax.axis('tight')
ax.axis('off')

# Create the table from DataFrame
table = pd.plotting.table(ax, df, loc='center', cellLoc='center')

plt.title("Sales Data Table from DataFrame")
plt.show()
16

21. Customizing Tables

Customizing tables in Matplotlib enhances data presentation by providing for increased readability and more attractive visual appearances. Here's an all-inclusive guide on creating and customizing tables using Matplotlib, which includes styling options for colors, fonts, and layouts.

Python
import matplotlib.pyplot as plt

data = [
    ['Year', 'Sales', 'Profit'],
    [2021, 15000, 3000],
    [2022, 20000, 5000],
    [2023, 25000, 7000]
]
fig, ax = plt.subplots()
ax.axis('tight')
ax.axis('off')

# Create the table with row and column labels
table = ax.table(cellText=data,
                 loc='center',
                 cellLoc='center',)

plt.title("Customized Sales Data Table")
plt.show()
17

Saving and Exporting Figures

Primarily, saving and exporting figures in Matplotlib utilizes the savefig() function. This function allows you to save your plots in a variety of formats, including PNG, PDF, SVG, and JPG, among others.

22. Saving figures in Different formats (Pdf, PNG, etc.)

You mainly use the savefig() function in Matplotlib for saving figures in different formats. It is possible to export any visualization into various file types including PNG, PDF, SVG, and JPEG.

Python
import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create the plot
plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Save the figure in multiple formats with custom settings
for fmt in ['png', 'pdf', 'svg']:
    plt.savefig(f'sine_wave.{fmt}', dpi=300, bbox_inches='tight')

plt.show()
18

23. Adjusting DPI and Figure size

One should alter the DPI or figure size for controlling the resolution and size of the plots with Matplotlib. Here is the detailed guide for effective management.

a. Creating figure with specified size and DPI

Python
import matplotlib.pyplot as plt

# Create a figure with specific size and DPI
plt.figure(figsize=(8, 6), dpi=100)     # 8 inches wide, 6 inches tall, 100 DPI
plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Figure with Custom Size and DPI')
plt.show()
19

b. Changing figure size after creation

Python
fig = plt.figure()
plt.plot([1, 2, 3], [1, 4, 9])

# Change figure size and DPI
fig.set_size_inches(10, 5)     # Set new size
fig.set_dpi(150)               # Set new DPI
plt.title('Updated Figure Size and DPI')
plt.show()
20

c. Using 'rcParams' for Global Settings

Python
import matplotlib.pyplot as plt

# Set default figure size and DPI globally
plt.rcParams['figure.figsize'] = (10, 5)
plt.rcParams['figure.dpi'] = 150

# Now all figures will use these settings by default
plt.plot([1, 2, 3], [1, 4, 9])
plt.title('Global Default Settings Applied')
plt.show()
21

Advanced Features

With the following advanced features in Matplotlib, you can get into annotations and texts in plots, customizing of ticks and tick labels, as well as using stylesheets for consistent formatting including details on all these.

24. Annotations and Text in Plots

Annotations are informative text that you add to specific points in your plots. They add clarity and help you understand the trend or behavior of what is happening. Annotate() uses the arrow function to mark points in your data.

Python
import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)

# Adding an annotation
plt.annotate('Local Max', xy=(1.57, 1), xytext=(3, 0.5),
             arrowprops=dict(facecolor='black', arrowstyle='->'))

plt.title('Sine Wave with Annotation')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()
22

25. Customizing Ticks and Tick Label

Customize your ticks and labels to make your plots more readable. You can change the location, appearance and format of your ticks through several methods.

Python
import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)

# Customizing ticks
plt.xticks(ticks=[0, 1, 2, 3], labels=['Zero', 'One', 'Two', 'Three'])
plt.yticks(fontsize=10)

plt.title('Sine Wave with Customized Ticks')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()
23

26. Stylesheets for Consistent Formatting

Matplotlib offers you the capability to define a stylesheet that will be applied for consistent formatting throughout multiple visualizations. You may use the available styles or design your own.

Python
plt.style.use('ggplot')  # Using a built-in style

# Example plot
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
plt.plot(x, y)
plt.title("Using ggplot Style")
plt.show()
24

Conclusion

To sum it up, 25+ Most Used snippets of Matplotlib encourages efficiency and reuse which results in the development of common tasks without rewriting a lot of code. Snippets encourage modularity in code which makes it cleaner as well as more maintainable. Moreover, they allow for personalization using features such as annotations, customized ticks and stylesheets which makes plots more informative and aesthetically pleasing. Snippets can be used with other libraries like Pandas to make the transition from data processing to visualization easier.


Next Article

Similar Reads