Formatting Currency Plots with Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to use Matplotlib to format the y-axis labels of a plot to display dollar signs. This is particularly useful when working with financial data or any data that requires currency formatting.

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/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/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`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") 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`") subgraph Lab Skills python/comments -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} python/with_statement -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} matplotlib/line_plots -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} python/booleans -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} python/tuples -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} python/dictionaries -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} python/importing_modules -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} python/standard_libraries -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} python/math_random -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} python/numerical_computing -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} python/data_visualization -.-> lab-48691{{"`Formatting Currency Plots with Matplotlib`"}} end

Import Necessary Libraries

First, we need to import the necessary libraries. We will be using matplotlib.pyplot to create our plot and format the y-axis labels.

import matplotlib.pyplot as plt

Create the Plot

Next, let's create a simple plot to work with. We will use NumPy to generate some random data to plot.

import numpy as np

## Generate random data
np.random.seed(19680801)
data = 100 * np.random.rand(20)

## Create the plot
fig, ax = plt.subplots()
ax.plot(data)

Format Y-Axis Labels with Dollar Signs

Now, let's format the y-axis labels to display dollar signs. We will use the StrMethodFormatter class from the matplotlib.ticker module to format the labels.

import matplotlib.ticker as ticker

## Format y-axis labels with dollar signs
fmt = '${x:,.2f}'
tick = ticker.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick)

In the above code, we create a StrMethodFormatter object with the format string '$ {x:,.2f}'. This format string specifies that we want a dollar sign followed by a space, followed by a comma-separated number with two decimal places.

Next, we create a Tick object using the StrMethodFormatter object we just created. Finally, we set the y-axis major formatter to the Tick object.

Customize Tick Parameters

We can also customize the tick parameters to further adjust the appearance of our plot. In this example, we will change the color of the tick labels to green and move them to the right side of the plot.

## Customize tick parameters
ax.tick_params(axis='y', which='major', labelcolor='green', labelright=True)

In the above code, we use the tick_params method to customize the y-axis tick parameters. We set the axis parameter to 'y' to specify that we are customizing the y-axis, and the which parameter to 'major' to specify that we are customizing the major ticks. We set the labelcolor parameter to 'green' to change the color of the tick labels, and the labelright parameter to True to move the tick labels to the right side of the plot.

Display the Plot

Finally, we can display our plot using the show method.

plt.show()

Summary

In this lab, we learned how to use Matplotlib to format y-axis labels with dollar signs. We used the StrMethodFormatter class from the matplotlib.ticker module to format the labels, and customized the tick parameters to further adjust the appearance of our plot.

Other Python Tutorials you may like