Matplotlib Style Sheets

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Matplotlib is a powerful data visualization library in Python. It allows you to create a variety of plots, such as scatter plots, histograms, bar graphs, and more. The style sheets reference script demonstrates the different available style sheets on a common set of example plots. In this lab, you will learn how to use Matplotlib style sheets to customize the appearance of your plots.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/PlottingDataGroup -.-> matplotlib/bar_charts("`Bar Charts`") matplotlib/PlottingDataGroup -.-> matplotlib/histograms("`Histograms`") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("`Heatmaps`") matplotlib/PlotCustomizationGroup -.-> matplotlib/titles_labels("`Adding Titles and Labels`") matplotlib/PlotCustomizationGroup -.-> matplotlib/grid_config("`Grid Configuration`") matplotlib/PlotCustomizationGroup -.-> matplotlib/text_annotations("`Text Annotations`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/matplotlib_config("`Customizing Matplotlib Configurations`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("`Catching Exceptions`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/with_statement -.-> lab-48964{{"`Matplotlib Style Sheets`"}} matplotlib/importing_matplotlib -.-> lab-48964{{"`Matplotlib Style Sheets`"}} matplotlib/figures_axes -.-> lab-48964{{"`Matplotlib Style Sheets`"}} matplotlib/line_plots -.-> lab-48964{{"`Matplotlib Style Sheets`"}} matplotlib/bar_charts -.-> lab-48964{{"`Matplotlib Style Sheets`"}} matplotlib/histograms -.-> lab-48964{{"`Matplotlib Style Sheets`"}} matplotlib/heatmaps -.-> lab-48964{{"`Matplotlib Style Sheets`"}} matplotlib/titles_labels -.-> lab-48964{{"`Matplotlib Style Sheets`"}} matplotlib/grid_config -.-> lab-48964{{"`Matplotlib Style Sheets`"}} matplotlib/text_annotations -.-> lab-48964{{"`Matplotlib Style Sheets`"}} matplotlib/matplotlib_config -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/variables_data_types -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/booleans -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/conditional_statements -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/for_loops -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/lists -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/tuples -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/dictionaries -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/function_definition -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/default_arguments -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/importing_modules -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/standard_libraries -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/catching_exceptions -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/math_random -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/data_collections -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/numerical_computing -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/data_visualization -.-> lab-48964{{"`Matplotlib Style Sheets`"}} python/build_in_functions -.-> lab-48964{{"`Matplotlib Style Sheets`"}} end

Import libraries

Before you get started, you need to import the necessary libraries. In this lab, you will be using Matplotlib and NumPy.

import matplotlib.pyplot as plt
import numpy as np

Define the plot functions

Next, you need to define the plot functions that will be used to create the example plots. In this step, you will define the following plot functions:

  • plot_scatter(): creates a scatter plot
  • plot_colored_lines(): plots lines with colors following the style color cycle
  • plot_bar_graphs(): creates a bar graph
  • plot_colored_circles(): plots circle patches
  • plot_image_and_patch(): plots an image with a circular patch
  • plot_histograms(): creates histograms
def plot_scatter(ax, prng, nb_samples=100):
    """Scatter plot."""
    for mu, sigma, marker in [(-.5, 0.75, 'o'), (0.75, 1., 's')]:
        x, y = prng.normal(loc=mu, scale=sigma, size=(2, nb_samples))
        ax.plot(x, y, ls='none', marker=marker)
    ax.set_xlabel('X-label')
    ax.set_title('Axes title')
    return ax


def plot_colored_lines(ax):
    """Plot lines with colors following the style color cycle."""
    t = np.linspace(-10, 10, 100)

    def sigmoid(t, t0):
        return 1 / (1 + np.exp(-(t - t0)))

    nb_colors = len(plt.rcParams['axes.prop_cycle'])
    shifts = np.linspace(-5, 5, nb_colors)
    amplitudes = np.linspace(1, 1.5, nb_colors)
    for t0, a in zip(shifts, amplitudes):
        ax.plot(t, a * sigmoid(t, t0), '-')
    ax.set_xlim(-10, 10)
    return ax


def plot_bar_graphs(ax, prng, min_value=5, max_value=25, nb_samples=5):
    """Plot two bar graphs side by side, with letters as x-tick labels."""
    x = np.arange(nb_samples)
    ya, yb = prng.randint(min_value, max_value, size=(2, nb_samples))
    width = 0.25
    ax.bar(x, ya, width)
    ax.bar(x + width, yb, width, color='C2')
    ax.set_xticks(x + width, labels=['a', 'b', 'c', 'd', 'e'])
    return ax


def plot_colored_circles(ax, prng, nb_samples=15):
    """
    Plot circle patches.

    NB: draws a fixed amount of samples, rather than using the length of
    the color cycle, because different styles may have different numbers
    of colors.
    """
    for sty_dict, j in zip(plt.rcParams['axes.prop_cycle'](),
                           range(nb_samples)):
        ax.add_patch(plt.Circle(prng.normal(scale=3, size=2),
                                radius=1.0, color=sty_dict['color']))
    ax.grid(visible=True)

    ## Add title for enabling grid
    plt.title('ax.grid(True)', family='monospace', fontsize='small')

    ax.set_xlim([-4, 8])
    ax.set_ylim([-5, 6])
    ax.set_aspect('equal', adjustable='box')  ## to plot circles as circles
    return ax


def plot_image_and_patch(ax, prng, size=(20, 20)):
    """Plot an image with random values and superimpose a circular patch."""
    values = prng.random_sample(size=size)
    ax.imshow(values, interpolation='none')
    c = plt.Circle((5, 5), radius=5, label='patch')
    ax.add_patch(c)
    ## Remove ticks
    ax.set_xticks([])
    ax.set_yticks([])


def plot_histograms(ax, prng, nb_samples=10000):
    """Plot 4 histograms and a text annotation."""
    params = ((10, 10), (4, 12), (50, 12), (6, 55))
    for a, b in params:
        values = prng.beta(a, b, size=nb_samples)
        ax.hist(values, histtype="stepfilled", bins=30,
                alpha=0.8, density=True)

    ## Add a small annotation.
    ax.annotate('Annotation', xy=(0.25, 4.25),
                xytext=(0.9, 0.9), textcoords=ax.transAxes,
                va="top", ha="right",
                bbox=dict(boxstyle="round", alpha=0.2),
                arrowprops=dict(
                          arrowstyle="->",
                          connectionstyle="angle,angleA=-95,angleB=35,rad=10"),
                )
    return ax

Define the plot function

Now, you need to define the plot_figure() function that will set up and plot the demonstration figure with a given style. This function will call each of the plot functions defined in Step 2.

def plot_figure(style_label=""):
    """Setup and plot the demonstration figure with a given style."""
    ## Use a dedicated RandomState instance to draw the same "random" values
    ## across the different figures.
    prng = np.random.RandomState(96917002)

    fig, axs = plt.subplots(ncols=6, nrows=1, num=style_label,
                            figsize=(14.8, 2.8), layout='constrained')

    ## make a suptitle, in the same style for all subfigures,
    ## except those with dark backgrounds, which get a lighter color:
    background_color = mcolors.rgb_to_hsv(
        mcolors.to_rgb(plt.rcParams['figure.facecolor']))[2]
    if background_color < 0.5:
        title_color = [0.8, 0.8, 1]
    else:
        title_color = np.array([19, 6, 84]) / 256
    fig.suptitle(style_label, x=0.01, ha='left', color=title_color,
                 fontsize=14, fontfamily='DejaVu Sans', fontweight='normal')

    plot_scatter(axs[0], prng)
    plot_image_and_patch(axs[1], prng)
    plot_bar_graphs(axs[2], prng)
    plot_colored_lines(axs[3])
    plot_histograms(axs[4], prng)
    plot_colored_circles(axs[5], prng)

    ## add divider
    rec = Rectangle((1 + 0.025, -2), 0.05, 16,
                    clip_on=False, color='gray')

    axs[4].add_artist(rec)

Plot the demonstration figure for each style sheet

Finally, you need to plot the demonstration figure for each available style sheet. You can do this by looping through the style_list and calling the plot_figure() function for each style sheet.

if __name__ == "__main__":

    ## Set up a list of all available styles, in alphabetical order but
    ## the `default` and `classic` ones, which will be forced resp. in
    ## first and second position.
    ## styles with leading underscores are for internal use such as testing
    ## and plot types gallery. These are excluded here.
    style_list = ['default', 'classic'] + sorted(
        style for style in plt.style.available
        if style != 'classic' and not style.startswith('_'))

    ## Plot a demonstration figure for every available style sheet.
    for style_label in style_list:
        with plt.rc_context({"figure.max_open_warning": len(style_list)}):
            with plt.style.context(style_label):
                plot_figure(style_label=style_label)

    plt.show()

Summary

In this lab, you learned how to use Matplotlib style sheets to customize the appearance of your plots. You learned how to define plot functions and use them to create a demonstration figure with a given style sheet. By following the steps outlined in this lab, you can apply Matplotlib style sheets to your own plots to create professional-looking data visualizations.