Introduction
This tutorial will guide you through the step-by-step process of creating a bar graph using Python's Matplotlib library. The example in this tutorial shows how to use the default units of centimeters and inches, how to set the x and y units using various keywords, and how to set the x-limits using scalars or units.
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.
Import Required Libraries
In this step, we need to import the required libraries that we will use to create the bar graph. We will be using Matplotlib and numpy libraries.
import matplotlib.pyplot as plt
import numpy as np
Create Data for the Bar Graph
In this step, we need to create data for the bar graph. We will use the numpy library to create an array of values that we will use for the bar graph.
from basic_units import cm, inch
cms = cm * np.arange(0, 10, 2)
bottom = 0 * cm
width = 0.8 * cm
Create the Bar Graph with Default Units
In this step, we will create the bar graph with default units using Matplotlib's bar method. We will use the bottom parameter to set the bottom of the bars to 0.
fig, axs = plt.subplots(2, 2)
axs[0, 0].bar(cms, cms, bottom=bottom)
Set the x and y Units for the Bar Graph
In this step, we will set the x and y units for the bar graph using various keywords. We will use the xunits and yunits parameters to set the x and y units to centimeters and inches.
axs[0, 1].bar(cms, cms, bottom=bottom, width=width, xunits=cm, yunits=inch)
Set the x-limits Using Scalars or Units
In this step, we will set the x-limits using scalars or units. We will use the set_xlim method to set the x-limits. We will set the x-limits to 2 and 6 using scalars in the current units for the bar graph in the second row and first column. We will set the x-limits to 2 cm and 6 cm using units for the bar graph in the second row and second column.
axs[1, 0].bar(cms, cms, bottom=bottom, width=width, xunits=inch, yunits=cm)
axs[1, 0].set_xlim(2, 6)
axs[1, 1].bar(cms, cms, bottom=bottom, width=width, xunits=inch, yunits=inch)
axs[1, 1].set_xlim(2 * cm, 6 * cm)
Display the Bar Graph
In this step, we will display the bar graph using Matplotlib's show method.
fig.tight_layout()
plt.show()
Summary
In this tutorial, we have learned how to create a bar graph using Matplotlib library in Python. We have learned how to use the default units of centimeters and inches, how to set the x and y units using various keywords, and how to set the x-limits using scalars or units.