UbuntuUbuntu Based

How To Install Matplotlib on Ubuntu 24.04 LTS

Install Matplotlib on Ubuntu 24.04

Matplotlib stands as one of the most powerful and versatile data visualization libraries in the Python ecosystem. For Ubuntu 24.04 LTS (Noble Numbat) users, implementing this essential tool opens up tremendous opportunities for creating publication-quality graphs, interactive plots, and complex visualizations for scientific research, data analysis, and reporting. Whether you’re a researcher analyzing experimental data, a data scientist exploring patterns, or a developer building data-driven applications, Matplotlib provides the foundation for effectively communicating insights through visual representation.

This comprehensive guide explores multiple methods for installing Matplotlib on Ubuntu 24.04 LTS, catering to different use cases and technical preferences. From straightforward system-wide installations to specialized environments for scientific computing, each approach offers distinct advantages depending on your specific requirements. By following these instructions, you’ll establish a robust visualization toolkit that integrates seamlessly with other scientific Python libraries like NumPy, Pandas, and SciPy.

Table of Contents

What is Matplotlib?

Matplotlib is a comprehensive Python library designed for creating static, animated, and interactive visualizations. Developed by John Hunter in 2003 as a way to emulate MATLAB’s plotting capabilities in Python, Matplotlib has evolved into an essential tool for the scientific Python ecosystem. The library provides an object-oriented API for embedding plots into applications and a state-based interface through its pyplot module that closely resembles MATLAB’s command syntax.

At its core, Matplotlib operates on a hierarchical structure of objects. The top-level object is the Figure, which serves as a container for all plot elements. Within a Figure, one or more Axes objects manage coordinate systems for plotting. This architecture allows for remarkable flexibility, enabling everything from simple line plots to complex multi-panel visualizations with custom styling.

Matplotlib supports a wide range of plot types including:

Line plots for time series and function visualization. Scatter plots for displaying relationships between variables. Bar charts and histograms for categorical and distribution analysis. Pie charts for showing proportions. 3D plots for three-dimensional data representation. Contour plots for showing equi-valued lines. Image display for working with arrays and photographs. Geographic projections for map-based visualizations.

The library excels at producing publication-quality output in various formats including PNG, PDF, SVG, EPS, and interactive displays. Its integration with Jupyter notebooks has made it particularly popular in data science workflows, allowing for iterative exploration and presentation in a single environment.

While newer libraries like Seaborn (built on Matplotlib), Plotly, and Bokeh offer specialized features for statistical visualization or interactive web-based plots, Matplotlib remains the foundation of Python’s visualization ecosystem due to its comprehensive feature set, extensive documentation, and mature codebase.

Prerequisites for Installation

Before installing Matplotlib on Ubuntu 24.04 LTS, ensure your system meets the necessary requirements and is properly prepared. Following these preliminary steps will help avoid common installation issues and ensure a smooth setup process.

System Update

Start by updating your Ubuntu system to ensure all packages are current. Open a terminal window and run:

sudo apt update sudo apt upgrade

This process may take several minutes depending on your internet connection speed and how recently your system was updated. It’s crucial to start with an updated system to avoid dependency conflicts and security vulnerabilities.

Python Installation Verification

Ubuntu 24.04 LTS comes with Python pre-installed, but it’s important to verify the version:

python3 --version

Ubuntu 24.04 LTS typically includes Python 3.12, which works well with current Matplotlib releases. If for some reason Python is not installed or you need a different version, you can install it with:

sudo apt install python3

Essential Development Packages

Several development packages may be required for compiling certain Matplotlib dependencies:

sudo apt install build-essential python3-dev

These packages provide the necessary compilers and header files that might be needed during the installation process, especially if Matplotlib needs to build components from source.

Method 1: Installing Matplotlib Using APT Package Manager

The simplest and most straightforward method to install Matplotlib on Ubuntu 24.04 LTS is through the Advanced Package Tool (APT), Ubuntu’s native package management system. This approach ensures system-wide availability and compatibility with other Ubuntu packages.

Installation Steps

Open a terminal window and execute the following commands:

sudo apt update sudo apt install python3-matplotlib

This command installs the Matplotlib package along with all its dependencies. The installation typically completes within a few minutes, depending on your internet connection and system performance.

Verification

After installation, verify that Matplotlib was installed correctly by checking the version:

python3 -c "import matplotlib; print(matplotlib.__version__)"

This command should display the version number of the installed Matplotlib package without any error messages. To further confirm functionality, try running a simple example:

python3 -c "import matplotlib.pyplot as plt; plt.plot(); plt.ylabel('some numbers'); plt.savefig('test.png'); print('Plot saved to test.png')"

If successful, this command will create a simple line plot and save it as ‘test.png‘ in the current directory.

Method 2: Installing Matplotlib Using PIP (Python Package Index)

Python’s Package Installer (PIP) offers access to the latest Matplotlib versions directly from the Python Package Index (PyPI). This method provides more control over the specific version installed and allows easier upgrades when new releases become available.

Installing PIP

First, ensure PIP is installed and up to date on your system:

sudo apt install python3-pip pip3 --version pip3 install --upgrade pip

Installing Matplotlib via PIP

With PIP ready, you can install Matplotlib using one of two approaches:

System-wide installation:

sudo pip3 install matplotlib

This installs Matplotlib for all users on the system, but requires administrative privileges and may interfere with packages managed by APT.

User-specific installation:

pip3 install --user matplotlib

This installs Matplotlib only for the current user, avoiding potential conflicts with system packages and not requiring administrator privileges. Packages are installed to ~/.local/lib/python3.x/site-packages/.

Handling Externally-Managed-Environment Error

Ubuntu 24.04 implements Python’s latest PEP 668 standard, which may result in an “externally-managed-environment” error when trying to install packages via PIP. This is a safeguard to prevent conflicts between APT and PIP. To work around this:

Option 1: Use the –break-system-packages flag (not recommended for production systems):

pip3 install --break-system-packages matplotlib

Option 2: Use the –user flag (safer approach):

pip3 install --user matplotlib

Option 3: Use virtual environments (recommended approach, covered in the next section).

Installing Additional Dependencies

For full functionality, especially for specialized backends, install these additional packages:

pip3 install --user numpy scipy pillow

Verification

Verify the installation with:

python3 -c "import matplotlib; print(matplotlib.__version__)"

The PIP installation method gives you access to the latest Matplotlib features and bug fixes. It provides greater control over specific versions and makes upgrading straightforward. However, it may create conflicts with system packages if not managed carefully, particularly when using system-wide installation. For development work or when specific versions are required, this method offers significant advantages over the APT approach.

Method 3: Installing Matplotlib in Python Virtual Environments

Virtual environments provide isolated Python environments where packages can be installed without affecting the system Python installation. This approach is considered best practice for Python development as it allows for project-specific dependencies and avoids potential conflicts between packages.

Creating a Virtual Environment

Ubuntu 24.04 LTS includes the venv module in its default Python installation. To create a virtual environment:

sudo apt install python3-venv python3 -m venv ~/matplotlib_env

This creates a new virtual environment named “matplotlib_env” in your home directory. You can choose any name or location for your environment.

Activating the Environment

Before installing packages, activate the virtual environment:

source ~/matplotlib_env/bin/activate

Your command prompt will change to indicate that the virtual environment is active, typically by showing the environment name in parentheses at the beginning of the prompt.

Installing Matplotlib in the Virtual Environment

With the environment activated, install Matplotlib using PIP:

(matplotlib_env) $ pip install matplotlib

Note that within the virtual environment, you can use ‘pip’ instead of ‘pip3’, and you don’t need the –user flag or sudo, as you’re installing into the isolated environment.

Installing the Scientific Stack

For a complete scientific Python environment, install additional packages:

(matplotlib_env) $ pip install numpy scipy pandas jupyter

Creating a Requirements File

For reproducibility, create a requirements.txt file that lists all installed packages:

(matplotlib_env) $ pip freeze > requirements.txt

This file can be used to recreate the environment on another system or after a fresh installation:

(matplotlib_env) $ pip install -r requirements.txt

Deactivating the Environment

When finished working with Matplotlib, deactivate the virtual environment:

(matplotlib_env) $ deactivate

Virtual environments are particularly valuable for development work, research projects requiring specific package versions, or when working on multiple projects with different dependency requirements. They eliminate the risk of breaking system packages and provide clean, reproducible environments that can be easily shared with others.

Method 4: Installing Matplotlib Using Anaconda/Miniconda

Anaconda is a comprehensive Python distribution for scientific computing that includes Matplotlib, NumPy, SciPy, Pandas, and many other libraries pre-installed. Miniconda is a minimal installer for Conda, providing just the package manager and Python without the additional packages. Both offer powerful environment management capabilities specifically designed for data science and scientific computing.

Installing Miniconda

Miniconda provides a lighter-weight alternative to the full Anaconda distribution:

wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh

Follow the prompts during installation. When asked if you want to initialize Miniconda3, answer ‘yes’ to add the conda command to your PATH.

After installation, either restart your terminal or run:

source ~/.bashrc

Creating a Conda Environment

Create a new environment with Python and Matplotlib:

conda create -n matplotlib_env python=3.12 matplotlib

This command creates an environment named “matplotlib_env” with Python 3.12 and Matplotlib installed.

Activating the Conda Environment

Activate the environment to use it:

conda activate matplotlib_env

Installing the Scientific Stack

Install additional scientific packages as needed:

(matplotlib_env) $ conda install numpy scipy pandas jupyter

Conda excels at managing complex package dependencies, particularly for scientific and numerical libraries with compiled components. It handles the installation of binary dependencies seamlessly across different platforms, making it especially valuable for libraries like Matplotlib that rely on various system libraries.

The Anaconda/Miniconda approach is particularly beneficial for researchers and data scientists who need a comprehensive scientific computing environment with carefully managed dependencies. However, it introduces a separate package management system that operates independently from Ubuntu’s native APT system.

Installing Additional Dependencies and Backend Options

Matplotlib supports various backend systems that determine how plots are displayed or saved. Different backends offer various features and integration options with GUI frameworks.

Understanding Matplotlib Backends

Matplotlib backends fall into two categories:

User Interface Backends (Interactive): These allow for interactive features like zooming, panning, and saving from a GUI window. Examples include Qt5Agg, TkAgg, and GTK4Agg.

Hardcopy Backends (Non-interactive): These generate static output formats like PNG, PDF, SVG, etc. Examples include Agg, PDF, SVG, and PS.

Installing GUI Backends

Depending on your preferred GUI framework, install the corresponding backend:

Qt Backend (Recommended for desktop applications):

sudo apt install python3-pyqt5 # Or in a virtual environment: pip install PyQt5

Gtk Backend:

sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-4.0 # Or in a virtual environment: pip install PyGObject

Tk Backend:

sudo apt install python3-tk # Or in a virtual environment: pip install tk

Setting Up LaTeX Support

For high-quality mathematical typesetting in plots, install LaTeX support:

sudo apt install texlive-latex-extra dvipng cm-super

This enables Matplotlib to render beautiful mathematical equations in your plots using LaTeX formatting.

Installing Animation Support

For creating animations with Matplotlib, install the ffmpeg package:

sudo apt install ffmpeg

With ffmpeg installed, you can create animations and save them in various video formats including MP4, GIF, and others.

Testing Backend Configuration

To check which backend is currently active:

python3 -c "import matplotlib; print(matplotlib.get_backend())"

To test a specific backend:

python3 -c "import matplotlib; matplotlib.use('Qt5Agg'); import matplotlib.pyplot as plt; plt.figure(); plt.plot(); plt.show()"

Installing these additional components enhances Matplotlib’s capabilities substantially, enabling interactive applications, high-quality document preparation, and animated visualizations. The choice of backend depends on your specific requirements, with Qt and Gtk offering robust GUI integration for desktop applications, while LaTeX support is essential for academic or publication-quality outputs.

Configuring Matplotlib After Installation

After installing Matplotlib, customizing its configuration allows for more efficient workflows and consistent visualization styling across your projects.

Locating the Configuration Directory

Matplotlib stores its configuration in a directory that you can locate with:

python3 -c "import matplotlib; print(matplotlib.get_configdir())"

This typically points to ~/.config/matplotlib/ on Ubuntu 24.04 systems.

Creating a Custom Configuration File

Create or edit the matplotlibrc file to customize default settings:

mkdir -p ~/.config/matplotlib cp /path/to/matplotlib/mpl-data/matplotlibrc ~/.config/matplotlib/

You can find the template path with:

python3 -c "import matplotlib; print(matplotlib.matplotlib_fname())"

Common Configuration Settings

Edit the matplotlibrc file to customize various aspects of Matplotlib’s behavior:

# Set the default figure size and DPI figure.figsize: 10, 6 figure.dpi: 100 # Set default font properties font.family: sans-serif font.size: 12 font.sans-serif: DejaVu Sans, Arial, Helvetica, sans-serif # Set the default backend backend: Qt5Agg # Enable LaTeX for text rendering text.usetex: True # Only enable if you have LaTeX installed

Creating Custom Style Sheets

Style sheets provide a way to create reusable styling configurations:

from matplotlib import pyplot as plt import numpy as np # Create a style dictionary style = { 'axes.grid': True, 'grid.linestyle': '--', 'axes.facecolor': '#f0f0f0', 'font.size': 12, 'axes.labelsize': 14, 'xtick.labelsize': 10, 'ytick.labelsize': 10, 'axes.spines.top': False, 'axes.spines.right': False, } # Save the style plt.style.use(style) plt.savefig('mystyle.mplstyle')

Save this as mystyle.mplstyle in your Matplotlib config directory, then use it with:

plt.style.use('mystyle')

Proper configuration can significantly enhance your productivity with Matplotlib by establishing consistent styling across projects, setting appropriate defaults for your typical use cases, and optimizing for your specific environment. For teams or research groups, shared style sheets can ensure visualization consistency across different users and projects.

Testing Your Matplotlib Installation

After installation and configuration, it’s essential to test your Matplotlib setup to ensure all components are functioning correctly.

Basic Functionality Test

Create a simple script named matplotlib_test.py:

import matplotlib.pyplot as plt import numpy as np # Create sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Create a figure and axis fig, ax = plt.subplots(figsize=(8, 6)) # Plot the data ax.plot(x, y, label='sin(x)') # Add labels and title ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('Simple Sine Wave Plot') ax.legend() # Add grid ax.grid(True, linestyle='--', alpha=0.7) # Save the figure plt.savefig('test_plot.png', dpi=100) # Show the plot plt.show() print("Test completed successfully!")

Run the script with:

python3 matplotlib_test.py

This script tests several key features: basic plotting functionality, NumPy integration, figure creation, axis manipulation, legend creation, grid display, saving to file, and display via the selected backend.

Testing Different Plot Types

To ensure comprehensive functionality, test various plot types with this expanded script:

import matplotlib.pyplot as plt import numpy as np # Sample data x = np.linspace(0, 10, 30) y1 = np.sin(x) y2 = np.cos(x) categories = ['A', 'B', 'C', 'D', 'E'] values = # Create a figure with multiple subplots fig, axs = plt.subplots(2, 2, figsize=(12, 10)) # Line plot axs.plot(x, y1, 'b-', label='sin(x)') axs.plot(x, y2, 'r--', label='cos(x)') axs.set_title('Line Plot') axs.legend() # Scatter plot axs.scatter(x, y1, color='blue', alpha=0.7, label='sin(x)') axs.scatter(x, y2, color='red', alpha=0.7, label='cos(x)') axs.set_title('Scatter Plot') axs.legend() # Bar chart axs.bar(categories, values, color='green', alpha=0.7) axs.set_title('Bar Chart') axs.set_xlabel('Categories') axs.set_ylabel('Values') # Histogram axs.hist(np.random.normal(0, 1, 1000), bins=30, color='purple', alpha=0.7) axs.set_title('Histogram') axs.set_xlabel('Value') axs.set_ylabel('Frequency') # Add a main title fig.suptitle('Matplotlib Test: Multiple Plot Types', fontsize=16) # Adjust layout plt.tight_layout(rect=[0, 0, 1, 0.95]) # Save the figure plt.savefig('test_multiple_plots.png', dpi=120) # Display the figure plt.show() print("Comprehensive test completed successfully!")

These test scripts help verify that your Matplotlib installation is functioning correctly across different plot types and features. If any issues arise during testing, they can help pinpoint specific areas that might need troubleshooting.

Troubleshooting Common Installation Issues

Even with careful installation, you might encounter certain issues with Matplotlib on Ubuntu 24.04 LTS. Here are solutions to common problems:

Module Not Found Errors

If you encounter “No module named matplotlib” after installation:

Verify the installation path and Python path:

python3 -m site

Ensure you’re using the correct Python interpreter:

which python3

If using a virtual environment, confirm it’s activated correctly. For user installations, ensure ~/.local/bin is in your PATH:

echo $PATH export PATH="$HOME/.local/bin:$PATH"

Backend-Related Problems

If plots don’t display or you see backend-related errors:

Try switching to a non-interactive backend for testing:

import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # Rest of your code plt.savefig('test.png')

Install required backend dependencies as outlined in the “Installing Additional Dependencies” section. Check if your system has a display server running (especially important for headless servers).

Externally-Managed-Environment Error in Ubuntu 24.04

If you see an error about Python being in an externally managed environment:

Use virtual environments (recommended approach):

python3 -m venv myenv source myenv/bin/activate pip install matplotlib

Or use the –user flag for local installation:

pip install --user matplotlib

As a last resort (not recommended for production systems):

pip install --break-system-packages matplotlib

Font and Text Rendering Issues

If text appears incorrectly or you have font-related warnings:

Update the font cache:

sudo apt install fontconfig fc-cache -fv

Install additional fonts:

sudo apt install fonts-freefont-ttf

For LaTeX-related issues, ensure you’ve installed the required packages:

sudo apt install texlive-latex-extra dvipng cm-super

Upgrading and Maintaining Matplotlib

Keeping Matplotlib updated ensures access to the latest features, bug fixes, and security improvements.

Checking Current Version

To check your currently installed Matplotlib version:

python3 -c "import matplotlib; print(matplotlib.__version__)"

Upgrading Based on Installation Method

For APT installations:

sudo apt update sudo apt upgrade python3-matplotlib

For PIP installations:

# System-wide sudo pip3 install --upgrade matplotlib # User installation pip3 install --user --upgrade matplotlib

For virtual environment installations:

source ~/matplotlib_env/bin/activate pip install --upgrade matplotlib

For Conda installations:

conda activate matplotlib_env conda update matplotlib

Managing Dependencies

When upgrading, it’s often beneficial to update related packages:

pip install --upgrade numpy scipy pillow

For major version upgrades, review the Matplotlib changelog for potential breaking changes that might affect your existing code. Creating a backup of your configuration files before major upgrades helps ensure you can revert if necessary.

Practical Matplotlib Examples

To help you get started with your newly installed Matplotlib, here are some practical examples that demonstrate its capabilities.

Basic Line Plot with Customization

import matplotlib.pyplot as plt import numpy as np # Create data x = np.linspace(0, 10, 100) y = np.exp(-x/2) * np.sin(2*x) # Create figure and axis fig, ax = plt.subplots(figsize=(10, 6)) # Plot with customization ax.plot(x, y, 'b-', linewidth=2, label='$e^{-x/2} \sin(2x)$') ax.set_xlabel('x', fontsize=14) ax.set_ylabel('y', fontsize=14) ax.set_title('Damped Sine Wave', fontsize=16) ax.grid(True, linestyle='--', alpha=0.7) ax.legend(fontsize=12) # Customize appearance ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.set_facecolor('#f8f8f8') plt.tight_layout() plt.savefig('damped_sine.png', dpi=120) plt.show()

Data Visualization with Pandas Integration

import matplotlib.pyplot as plt import pandas as pd import numpy as np # Create sample data dates = pd.date_range('20230101', periods=100) data = pd.DataFrame({ 'A': np.cumsum(np.random.randn(100)), 'B': np.cumsum(np.random.randn(100) * 0.5 + 0.5), 'C': np.cumsum(np.random.randn(100) * 0.8 - 0.2) }, index=dates) # Plot the data fig, ax = plt.subplots(figsize=(12, 7)) data.plot(ax=ax, linewidth=2) # Customize ax.set_title('Cumulative Random Walks', fontsize=16) ax.set_xlabel('Date', fontsize=14) ax.set_ylabel('Value', fontsize=14) ax.grid(True, linestyle='--', alpha=0.7) ax.legend(fontsize=12) plt.tight_layout() plt.savefig('pandas_integration.png', dpi=120) plt.show()

These examples just scratch the surface of what’s possible with Matplotlib. As you become more familiar with the library, you can create increasingly sophisticated visualizations tailored to your specific data and communication needs.

Congratulations! You have successfully installed Matplotlib. Thanks for using this tutorial for installing Matplotlib on Ubuntu 24.04 LTS system. For additional help or useful information, we recommend you check the official Matplotlib website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button