Matplotlib Bar Chart

PythonPythonBeginner
Practice Now

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

Introduction

Matplotlib is a popular Python library used for data visualization. It provides a wide range of tools for creating charts, graphs, and other visualizations. In this tutorial, you will learn how to create a bar chart with gradients using Matplotlib.

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/FunctionsGroup(["`Functions`"]) 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/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/FunctionsGroup -.-> python/keyword_arguments("`Keyword Arguments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("`Heatmaps`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") 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/standard_libraries("`Common Standard Libraries`") 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-48755{{"`Matplotlib Bar Chart`"}} python/keyword_arguments -.-> lab-48755{{"`Matplotlib Bar Chart`"}} matplotlib/importing_matplotlib -.-> lab-48755{{"`Matplotlib Bar Chart`"}} matplotlib/figures_axes -.-> lab-48755{{"`Matplotlib Bar Chart`"}} matplotlib/heatmaps -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/variables_data_types -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/numeric_types -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/for_loops -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/lists -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/tuples -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/function_definition -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/default_arguments -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/importing_modules -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/standard_libraries -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/math_random -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/data_collections -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/numerical_computing -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/data_visualization -.-> lab-48755{{"`Matplotlib Bar Chart`"}} python/build_in_functions -.-> lab-48755{{"`Matplotlib Bar Chart`"}} end

Import the necessary libraries

First, we need to import the necessary libraries, which are NumPy and Matplotlib. NumPy is a library used for numerical computations, while Matplotlib is a library used for data visualization.

import matplotlib.pyplot as plt
import numpy as np

Set the random seed

We will set the random seed to ensure that we get the same random numbers every time we run the code. This is done using the np.random.seed() function.

np.random.seed(19680801)

Define the gradient image function

We need to define a function that will create a gradient image based on a colormap. This function will take in an axes object, the direction of the gradient, and the range of the colormap to be used. The function will then generate the gradient image and return it.

def gradient_image(ax, direction=0.3, cmap_range=(0, 1), **kwargs):
    """
    Draw a gradient image based on a colormap.

    Parameters
    ----------
    ax : Axes
        The axes to draw on.
    direction : float
        The direction of the gradient. This is a number in
        range 0 (=vertical) to 1 (=horizontal).
    cmap_range : float, float
        The fraction (cmin, cmax) of the colormap that should be
        used for the gradient, where the complete colormap is (0, 1).
    **kwargs
        Other parameters are passed on to `.Axes.imshow()`.
        In particular, *cmap*, *extent*, and *transform* may be useful.
    """
    phi = direction * np.pi / 2
    v = np.array([np.cos(phi), np.sin(phi)])
    X = np.array([[v @ [1, 0], v @ [1, 1]],
                  [v @ [0, 0], v @ [0, 1]]])
    a, b = cmap_range
    X = a + (b - a) / X.max() * X
    im = ax.imshow(X, interpolation='bicubic', clim=(0, 1),
                   aspect='auto', **kwargs)
    return im

Define the gradient bar function

Next, we need to define a function that will create a gradient bar. This function will take in the axes object, the x and y coordinates of the bar, the width of the bar, and the bottom position of the bar. The function will then create a gradient image for each bar and return it.

def gradient_bar(ax, x, y, width=0.5, bottom=0):
    for left, top in zip(x, y):
        right = left + width
        gradient_image(ax, extent=(left, right, bottom, top),
                       cmap=plt.cm.Blues_r, cmap_range=(0, 0.8))

Create the plot

Now, we can create the plot. We will first create a figure and an axes object. We will then set the x and y limits of the axes. We will create a gradient background using the gradient_image() function. Finally, we will create a random data set and use the gradient_bar() function to create the bar chart.

fig, ax = plt.subplots()
ax.set(xlim=(0, 10), ylim=(0, 1))

## background image
gradient_image(ax, direction=1, extent=(0, 1, 0, 1), transform=ax.transAxes,
               cmap=plt.cm.RdYlGn, cmap_range=(0.2, 0.8), alpha=0.5)

N = 10
x = np.arange(N) + 0.15
y = np.random.rand(N)
gradient_bar(ax, x, y, width=0.7)
plt.show()

Summary

In this tutorial, you learned how to create a bar chart with gradients using Matplotlib. You learned how to define the gradient image function and the gradient bar function, and how to create a plot using these functions. You also learned how to set the random seed and how to import the necessary libraries.

Other Python Tutorials you may like