Fix the Broken Legend
Intermediate · Fix the bug · from Matplotlib: Create Line, Bar, Scatter, and Pie Charts
From the lesson: Matplotlib: Create Line, Bar, Scatter, and Pie Charts
Imagine you have a spreadsheet with 10,000 rows of sales data. You could stare at those numbers for hours, or you could turn them into a chart and spot the trend in three seconds. That's the power of data visualization.
Read the lessonThis code tries to create a chart with a legend, but the legend shows no entries. Fix the bug so the legend displays ['Revenue', 'Expenses'].
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5]
revenue = [100, 120, 140, 160, 180]
expenses = [90, 95, 100, 110, 115]
fig, ax = plt.subplots()
ax.plot(months, revenue)
ax.plot(months, expenses)
ax.legend()
legend_texts = [t.get_text() for t in ax.get_legend().get_texts()]
print(legend_texts)
More Matplotlib exercises
- Build a Temperature Line ChartIntermediate
- Build a Fruit Sales Bar ChartIntermediate
- Create a Height vs Weight Scatter PlotIntermediate
- Predict the Figure PropertiesIntermediate
- Prepare Data for a Multi-Series ChartIntermediate
All Python exercises · 50 practice problems · Data Science & Machine Learning quiz