Get Started

Adding a legend

A legend can be useful when plotting multiple datasets to identify which plot is associated with a specific dataset. To add a legend, you can use the label argument. To display the legend on the plot, you can use the function plt.legend().

matplotlib.pyplot is imported as plt and lists stock_A and stock_B are available in your workspace.

This is a part of the course

“Introduction to Python for Finance”

View Course

Exercise instructions

  • Plot histograms for stock_A and stock_B and add labels to each plot ('Stock A' and 'Stock B').
  • Display the legend and the plot.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Plot stock_A and stock_B histograms
plt.hist(stock_A, bins=100, alpha=0.4, label=____)
plt.hist(stock_B, bins=100, alpha=0.4, label=____)

# Add the legend
____

# Display the plot
plt.show()

This exercise is part of the course

Introduction to Python for Finance

BeginnerSkill Level
4.7+
29 reviews

Build Python skills to elevate your finance career. Learn how to work with lists, arrays and data visualizations to master financial analyses.

In this chapter, you will be introduced to the Matplotlib package for creating line plots, scatter plots, and histograms.

Exercise 1: Visualization in PythonExercise 2: Importing matplotlib and pyplotExercise 3: Adding axis labels and titlesExercise 4: Multiple lines on the same plotExercise 5: ScatterplotsExercise 6: HistogramsExercise 7: What are applications of histograms in finance?Exercise 8: Is data normally distributed?Exercise 9: Comparing two histogramsExercise 10: Adding a legend

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free