Editor

Annotate the Maximum Value

Advanced · Write the code · from Advanced Matplotlib: Subplots, Dual Axes, Styles, Annotations

From the lesson: Advanced Matplotlib: Subplots, Dual Axes, Styles, Annotations

You know how to create a single chart. But real-world reports rarely have just one. A data analyst might need four charts side by side, each zoomed into a different slice of the same dataset.

Read the lesson

Given the prices list, find the index and value of the maximum price. Plot the data, then use ax.annotate() to label the peak point with the text 'Peak: $MAX' (where MAX is the actual max value). Also add a horizontal dashed line at the average price using ax.axhline(). Print the max value and the average (rounded to 1 decimal).

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
days = list(range(1, 11))
prices = [42, 45, 43, 48, 52, 49, 55, 53, 58, 54]
fig, ax = plt.subplots()
ax.plot(days, prices, marker='o')
# Find max value and its index
# Annotate the peak
# Add average reference line
# Print max and average

More Matplotlib Subplots exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz