Creating Boxes From Error Bars Using PatchCollection

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to create box plots from error bars using PatchCollection. Box plots are useful for displaying the range and distribution of data. By adding a rectangle patch defined by the limits of the bars in both the x- and y-directions, we can make a more visually appealing error bar plot.

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`"]) 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/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/error_bars("`Error Bars`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") 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-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/with_statement -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} matplotlib/importing_matplotlib -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} matplotlib/figures_axes -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} matplotlib/error_bars -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/for_loops -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/list_comprehensions -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/lists -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/tuples -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/function_definition -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/default_arguments -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/importing_modules -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/using_packages -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/standard_libraries -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/math_random -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/numerical_computing -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/data_visualization -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} python/build_in_functions -.-> lab-48718{{"`Creating Boxes From Error Bars Using PatchCollection`"}} end

Import Libraries

We will first import the necessary libraries, including numpy and matplotlib.

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle

Prepare Data

We will then prepare the data for our box plot. We will create some dummy data for the x and y values, as well as the error values.

## Number of data points
n = 5

## Dummy data
np.random.seed(19680801)
x = np.arange(0, n, 1)
y = np.random.rand(n) * 5.

## Dummy errors (above and below)
xerr = np.random.rand(2, n) + 0.1
yerr = np.random.rand(2, n) + 0.2

Create Function for Error Boxes

We will now create a function called make_error_boxes that will create the rectangle patch defined by the limits of the bars in both the x- and y-directions.

def make_error_boxes(ax, xdata, ydata, xerror, yerror, facecolor='r',
                     edgecolor='none', alpha=0.5):

    ## Loop over data points; create box from errors at each point
    errorboxes = [Rectangle((x - xe[0], y - ye[0]), xe.sum(), ye.sum())
                  for x, y, xe, ye in zip(xdata, ydata, xerror.T, yerror.T)]

    ## Create patch collection with specified colour/alpha
    pc = PatchCollection(errorboxes, facecolor=facecolor, alpha=alpha,
                         edgecolor=edgecolor)

    ## Add collection to axes
    ax.add_collection(pc)

    ## Plot errorbars
    artists = ax.errorbar(xdata, ydata, xerr=xerror, yerr=yerror,
                          fmt='none', ecolor='k')

    return artists

Create Figure and Axes

We will now create the figure and axes for our box plot using plt.subplots().

## Create figure and axes
fig, ax = plt.subplots(1)

Call Function to Create Error Boxes

We will now call the make_error_boxes() function to create the error boxes on our plot.

## Call function to create error boxes
_ = make_error_boxes(ax, x, y, xerr, yerr)

Display the Plot

Finally, we will display the plot using plt.show().

plt.show()

Summary

In this lab, we learned how to create box plots from error bars using PatchCollection in Matplotlib. By adding a rectangle patch defined by the limits of the bars in both the x- and y-directions, we were able to create a more visually appealing error bar plot.

Other Python Tutorials you may like