Matplotlib Library in Python

Matplotlib Library in Python

May 16th, 2026
183
20:00 Minutes

Are you curious how raw data becomes beautiful visualisations? If yes, read on. I have four years of practical experience in Python, with considerable experience creating effective plots using data visualization software. I will share helpful tips and lessons learned from my experience so that you can learn how to make effective use of visualisation.

In this blog, I will explain you what is matplotlib library in Python, its architecture and working, its real world applications and many more.

Let’s get started!

What is Matplotlib Library in Python?

Matplotlib is a Python library that is used for creating static, interactive and animated visualizations from data. It provides flexible and customizable plotting functions that help in understanding data patterns, trends and relationships effectively.

For example: Monthly Sales Analysis (Business Dashboard)

import matplotlib.pyplot as plt

# Monthly data
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [20000, 25000, 30000, 28000, 35000, 40000]

# Create line plot
plt.plot(months, sales, marker='o')

# Add details
plt.title("Monthly Sales Analysis")
plt.xlabel("Months")
plt.ylabel("Sales (in ₹)")
plt.grid()

# Show plot
plt.show()

matplotlib library in python

What this shows:

1. Tracks sales growth over time

2. Helps businesses:

  • Identify peak months
  • Detect drops in performance
  • Make better decisions (marketing, inventory etc.)

Read Also: Python Tutorial for Beginners

Features of Matplotlib

Matplotlib offers powerful features such as customization of colors, labels, styles and layouts. It also supports multiple plots in a single figure, which makes it a highly versatile for creating detailed and informative visualizations.

  • Dual Interfaces: Offers a fast, state based Pyplot API (similar to MATLAB) for quick scripts and a more powerful Object Oriented API for complex, highly customized figures.
  • Fine-Grained Customization: It allows precise control over colors, line styles, markers, fonts, legends and gridlines.
  • Publication Quality: Generates high-resolution figures (DPI control) in formats like PNG, PDF, SVG, EPS and PGF, which is ideal for academic journals.
  • LaTeX Support: Built-in TeX expression parser allows for mathematical notations and complex formulas directly in titles or labels.
  • Interactive Features: Supports zooming, panning and real-time updates within environments like Jupyter Notebooks.

Types of Matplotlib Plots

There are multiple types of plots that can be created with Matplotlib, ranging from simple line graphs/plots through scatter plots, histograms and finally pie charts, all of these have different intended uses as they provide visual means to categorise and quantify information.

1. Line Plot

A line plot illustrates point changes in relation to time through connecting lines. This type of visual representation allows for quick identification of trends, patterns or progression within continuous datasets.

For example:

import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5]
temp = [30, 32, 35, 33, 31]

plt.plot(days, temp)
plt.title("Temperature Trend")
plt.xlabel("Days")
plt.ylabel("Temperature")
plt.show()

line matplotlib plots

2. Bar Plot

A bar plot displays information via bars with the height of each bar indicating respective values; bar charts offer an easy method for comparing across multiple categories.

For example:

import matplotlib.pyplot as plt

products = ['A', 'B', 'C']
sales = [100, 150, 80]

plt.bar(products, sales)
plt.title("Product Sales")
plt.show()

bar matplotlib plots

3. Histogram

A histogram groups data into defined intervals (bins) and shows how often each interval contains data. This type of visualization allows for an easy means of analyzing data distribution and frequency.

For example:

import matplotlib.pyplot as plt

marks = [40, 50, 60, 70, 80, 90, 60, 70]

plt.hist(marks, bins=5)
plt.title("Marks Distribution")
plt.show()

histogram matplotlib plots

4. Scatter Plot

A scatter plot displays individual data points on a graph; while this does not create a direct line between them, it can provide insight into the relationship and possible correlation between two variables.

For example:

import matplotlib.pyplot as plt

height = [150, 160, 170, 180]
weight = [50, 60, 65, 80]

plt.scatter(height, weight)
plt.title("Height vs Weight")
plt.show()

scatter matplotlib plots

5. Pie Chart

A pie chart segments a circle into parts (slices) to allow for displaying the proportional contribution of each segment in relation to the total.

For example:

import matplotlib.pyplot as plt

labels = ['A', 'B', 'C']
sizes = [40, 35, 25]

plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Market Share")
plt.show()

pie chart matplotlib

6. Box Plot

A box plot displays the distribution of data using quartiles and the median, whilst additionally providing the user with outliers in order to gain insights about the amount of variability in the data set.

For example:

import matplotlib.pyplot as plt

scores = [10, 20, 30, 40, 50, 100]

plt.boxplot(scores)
plt.title("Score Distribution")
plt.show()

box matplotlib plots

7. Area Plot

An area plot is like a line plot but with the area filled underneath. It helps you see both trends and the overall magnitude of data.

For example:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 15, 25]

plt.fill_between(x, y)
plt.title("Area Plot")
plt.show()

area matplotlib plots

8. Heatmap

A heatmap uses colors to visually display values in a grid format. A heatmap will display color, so you can quickly identify trends, patterns and high/low values of the available data in large datasets.

For example:

import matplotlib.pyplot as plt
import numpy as np

data = np.array([[1, 2], [3, 4]])

plt.imshow(data)
plt.colorbar()
plt.title("Heatmap")
plt.show()

matplotlib heatmap

9. 3D Plot

3-D plotting uses 3 different axis (X, Y and Z). 3-D plotting allows for the visualization of complicated relationships and patterns that are not as easy to see in 2-D graphs.

For example:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]

ax.scatter(x, y, z)
plt.title("3D Plot")
plt.show()

3d matplotlib plots

10. Violin Plot

A violin plot displays both the distribution of data and the density of data. A violin plot allows you to understand how the data is dispersed and where the majority of the data points cluster.

For example:

import matplotlib.pyplot as plt
import numpy as np

# Step 1: Create sample data (3 different groups)
group1 = np.random.normal(50, 10, 100)
group2 = np.random.normal(60, 15, 100)
group3 = np.random.normal(70, 5, 100)

data = [group1, group2, group3]

# Step 2: Create the violin plot
plt.violinplot(data)

# Step 3: Add labels and title
plt.xticks([1, 2, 3], ['Group 1', 'Group 2', 'Group 3'])
plt.title("Violin Plot Example")
plt.ylabel("Values")

# Step 4: Show the plot
plt.show()

matplotlib plots violin

Read Also: Python Interview Questions and Answers

Prerequisites and Installation of Matplotlib

If you want to use Matplotlib, then you should know that to use it, you should already have a basic understanding of Python programming language and knowledge about how to manipulate data because it is easy for people who have little experience working with MATLAB to learn how to use Matplotlib due to PHP script web-based framework being able make installation process very simple through built-in features provided by common package managers such as PIP. After installing matplotlib, you will be able to start creating graphs/charts and plotting data becomes not complicated as there are a lot of example code and sample images found within the tutorial provided by author called "Data Visualization with Matplotlib."

  • Before you purchase matplotlib, check out the following first:
  • Python is installed already (preferably v3.7 or higher)
  • pip has been configured already
  • code editing tool/IDE VS Code/Jupyter Notebook/PyCharm

Installation Steps

Its installation is very simple, you just have to follow these steps:

1. Open your Terminal / Command Prompt

2. Type the following command:

pip install matplotlib

3. Press Enter

4. Wait for the installation to complete

After installation, you can check if it works by running this Python code:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

installation of matplotlib

Read Also: Pandas Interview Questions And Answers

How Matplotlib Works?

Matplotlib takes your data input and produces a visual representation by converting it into visual elements. It works in a stepwise manner, where data is passed through three stages of plotting function calls until the final visualization of the data has been rendered.

Three Main Layers of Matplotlib

Matplotlib follows a layered architecture that transforms raw data into visual plots through a structured pipeline. It uses the pyplot interface, artist objects and rendering backends to efficiently create, manage and display high quality graphical visualizations.

1. Scripting Layer (Pyplot Interface)

  • This is what you usually use: matplotlib.pyplot
  • Provides simple functions like plot, title, show
  • Works like MATLAB style plotting

2. Artist Layer (Object-Oriented Layer)

  • Everything visible in a plot is an Artist
  • Examples:

1. Figure (entire canvas)

2. Axes (plot area)

3. Line, Text, Labels

3. Backend Layer (Rendering Layer)

  • Responsible for displaying or saving plots
  • It has two types:

1. Interactive backends: show plots (Tkinter, Qt)

2. Non-interactive backends: save files (PNG, PDF)

Flow of Matplotlib: Step-by-step explanation

While creating plots may seem simple on the surface, but there is a structured flow happening behind the scenes. When you understand this flow, you can easily gain better control over your visualizations.

Let’s break it down step by step:

Step 1: Data Input

Every graph starts with a data.

For example:

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
x is the horizontal axis and y is the vertical axis

Step 2: Pyplot Calls

Pyplot is used to create plots in Matplotlib.

For example:

import matplotlib.pyplot as plt
plt.plot(x, y)

This command tells Matplotlib to create a line graph using the given data.

Step 3: Create Figure & Axes

Matplotlib creates a figure and axes to display the graph.

For example:

fig, ax = plt.subplots()
ax.plot(x, y)

The figure is the overall canvas and the axes are the area where the graph is drawn.

Step 4: Add Artists

Artists are the elements that make the graph clear and readable.

For example:

plt.title("Sample Graph")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

These include titles, labels and other visual elements.

Step 5: Backend Renders

The backend displays the final graph.

For example:

plt.show()

This command shows the graph on the screen.

You can also save it using:

plt.savefig("graph.png")

backend renders

Read Also: Python Libraries for Machine Learning

Python Matplotlib Real-World Applications

Matplotlib is widely used across different industries to visualize data from business analytics to scientific research. With its toolset, Matplotlib can assist people with transforming raw data into meaningful insights that they can use in their decision making processes as well as in identifying trends and patterns.

1. Weather Data Visualization

Using Matplotlib allows for easy analysis of temperature, precipitation and Humidity changes over a determined period of time. This provides insight into overall Climate change.

For example:

import matplotlib.pyplot as plt

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
temperature = [30, 32, 35, 33, 31]

plt.plot(days, temperature, marker='o')
plt.title("Weekly Temperature Trend")
plt.xlabel("Days")
plt.ylabel("Temperature (°C)")
plt.show()

weather data visualization

2. Student Performance Analysis

This enables educators to monitor each individual student's performance and compare grades based on Class.

For example:

import matplotlib.pyplot as plt

subjects = ['Math', 'Science', 'English']
marks = [85, 90, 78]

plt.bar(subjects, marks)
plt.title("Student Performance")
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.show()

performance analysis matplotlib

3. Stock Market Analysis

This enables individuals to visualize trends in Stock prices and variations throughout the time period analyzed; providing assistance with making financial decisions.

For example:

import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5]
prices = [100, 105, 102, 108, 110]

plt.plot(days, prices)
plt.title("Stock Price Trend")
plt.xlabel("Days")
plt.ylabel("Price")
plt.show()

stock market analysis matplotlib

4. Healthcare Data Monitoring

Hospitals use Matplotlib to track patient information (e.g. heart rate, blood pressure, etc.).

For example:

import matplotlib.pyplot as plt

time = [1, 2, 3, 4, 5]
heart_rate = [72, 75, 78, 76, 74]

plt.plot(time, heart_rate, color='red')
plt.title("Heart Rate Monitoring")
plt.xlabel("Time")
plt.ylabel("Heart Rate (bpm)")
plt.show()

healthcare data monitoring matplotlib

5. Traffic Flow Analysis

This provides Municipal Planners with the ability to analyze the movement of vehicles and identify areas of congestion.

For example:

import matplotlib.pyplot as plt

hours = ['8AM', '10AM', '12PM', '2PM', '4PM']
vehicles = [200, 150, 300, 250, 400]

plt.bar(hours, vehicles, color='orange')
plt.title("Traffic Flow Analysis")
plt.xlabel("Time")
plt.ylabel("Number of Vehicles")
plt.show()

traffic flow analysis matplotlib

6. Social Media Engagement Analysis

Matplotlib enables analasys and tracking of the number of times a piece of content has a "Like", "Comment" or "Share". This will assist marketers in determining the level of audience engagement and measure the effectiveness of their Marketing Responses.

For example:

import matplotlib.pyplot as plt

posts = ['Post1', 'Post2', 'Post3', 'Post4']
likes = [120, 200, 150, 300]

plt.plot(posts, likes, marker='o')
plt.title("Social Media Engagement")
plt.xlabel("Posts")
plt.ylabel("Likes")
plt.show()

social media engagement analysis matplotlib

7. Energy Consumption Analysis

Can be employed to monitor electric consumption in businesses or residential dwellings to help identify methods for optimizing overall energy use.

For example:

import matplotlib.pyplot as plt

months = ['Jan', 'Feb', 'Mar', 'Apr']
units = [250, 300, 280, 320]

plt.bar(months, units, color='green')
plt.title("Monthly Energy Consumption")
plt.xlabel("Months")
plt.ylabel("Units Consumed")
plt.show()

energy consumption analysis matplotlib

Read Also: NumPy Interview Questions and Answers

Matplotlib vs Seaborn vs Plotly: Key Differences

When faced with so many choices for a data visualization library, it can be hard to decide which one is best for you. Some libraries such as Matplotlib, Seaborn and Plotly have similar capabilities; however, there are some significant differences between them that allow you to decide which option is right for you.

Feature Matplotlib Seaborn Plotly
Ease of Use Moderate – requires more code but very flexible Easy – simple syntax with better defaults Easy – especially for interactive charts
Customization Very High – full control over every element Medium – less control than Matplotlib High – customizable but within framework limits
Visual Appearance Basic by default (needs styling) Attractive and modern by default Highly polished and interactive visuals
Interactivity No (static plots) No (static plots) Yes (zoom, hover, click features)
Best Use Case Learning, research, detailed control Statistical analysis and quick insights Dashboards, presentations, web apps
Learning Value Strong fundamentals (must-learn) Builds on Matplotlib (easy upgrade) Useful for real-world applications

Python(Matplotlib) vs. MATLAB

Both Matlab and Matplotlib offer excellent ways to visualize data. However, due to the nature of the programming languages used, Matlab is generally a better option due to its integrated environment, whereas Python has more open-source flexibility and access to more components. The choice between these two languages depends on your specific needs and access.

Features Python (Matplotlib) MATLAB
Cost Free and open-source Paid software (license required)
Ease of Use Slight learning curve; flexible but needs coding Easier for beginners with built-in functions
Flexibility Highly customizable; integrates with many libraries (NumPy, Pandas) Less flexible compared to Python ecosystem
Performance Good performance; depends on libraries used Optimized for numerical computing and matrix operations
Visualization Quality High-quality plots with customization options High-quality plots with simpler commands
Community Support Huge global community; lots of tutorials and resources Strong but smaller community compared to Python
Use Cases Data science, machine learning, web apps, automation Engineering, simulations, academic research

Advantages of Matplotlib

Matplotlib is popular for its simplicity as well as for being customizable enough that you won’t be constrained by any limits on what you can create. It provides the tools needed for beginners and experienced users alike to create clear visualizations that communicate their data effectively.

Here are some of them:

1. Ease of Use: It provides a straightforward and intuitive interface for creating a wide variety of plots and charts.

2. Customizability: The library offers extensive customization options allowing users to tailor visuals to precise specifications.

3. Community Support: It has robust community support that can be a boon in troubleshooting issues.

4. Wide Variety of Plots: Matplotlib supports numerous plot types such as line plots, bar charts, histograms, scatter plots, pie charts and even 3D visualizations. This makes it a one stop solution for most data visualization needs.

5. Integration with Python Ecosystem: It works seamlessly with libraries like NumPy and Pandas, which allows you to directly visualize processed data without complex conversions.

Disadvantages of Matplotlib

Although Matplotlib has many positive attributes, it can feel complex when it comes to the advanced customization of visualizations. The syntax used within Matplotlib can be lengthy compared to more modern libraries and as a result creating highly interactive or aesthetically pleasing visualizations often requires additional resources or libraries.

Here are some of them:

1. Steep Learning Curve for Advanced Features: While basic plots are easy, it can master advanced customization can be complex and time consuming.

2. Verbose Syntax: Compared to modern libraries like Seaborn or Plotly, Matplotlib sometimes requires more lines of code to create aesthetically pleasing visualizations.

3. Less Interactive by Default: It is primarily static. Interactive features are limited unless combined with additional tools or libraries.

Wrapping Up

In conclusion, Matplotlib stands as a powerful and versatile tool for transforming raw data into meaningful visual insights. From basic plots to real-world applications, its flexibility and depth make it essential for data analysis, which helps the users communicate patterns, trends and decisions effectively.

After reading this, you should start practicing by creating simple plots and gradually explore advanced features to strengthen your skills

FAQ on Matplotlib Library in Python

1. What does the acronym Matplotlib mean?

The name was coined by combining "MATLAB" and "plotting library," which reflects the fact that it was inspired by MATLAB's graphing capabilities.

2. Who created Matplotlib?

The creator of Matplotlib is John D. Hunter and the project started in 2003, as he wanted to develop a plotting library in Python that emulates what is available with MATLAB.

3. Does Excel employ Matplotlib?

No, Microsoft Excel does not make use of Matplotlib; Excel provides its own charting tools which differ from the purpose of Matplotlib - an open source programming interface used by many software applications written in Python to create visual representations of data.

4. What is the latest version of Matplotlib?

The latest stable version of Matplotlib is 3.10.8, released on November 13, 2025.

About the Author
Sanjay Prajapat
About the Author

Sanjay Prajapat is a Data Engineer and technology writer with expertise in Python, SQL, data visualization, and machine learning. He simplifies complex concepts into engaging content, helping beginners and professionals learn effectively while exploring emerging fields like AI, ML, and cybersecurity in today’s evolving tech landscape.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.