4. Identify the error in this code that tries to highlight and annotate a point:
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [5, 7, 9]
plt.plot(x, y)
plt.axhspan(6, 8, color='green')
plt.annotate('Important', xy=(2, 7), xytext=(2, 9), arrowprops='->')
plt.show()
medium
A. plt.axhspan should use x values, not y values
B. plt.plot should use scatter instead for annotation
C. xytext coordinates must be inside the plot range
D. arrowprops should be a dictionary, not a string
Solution
Step 1: Check plt.axhspan usage
plt.axhspan(6, 8, color='green') is correct to highlight horizontal area between y=6 and y=8.
Step 2: Check plt.annotate arrowprops parameter
arrowprops must be a dictionary describing arrow style, not a string like '->'.
Final Answer:
arrowprops should be a dictionary, not a string -> Option D
Quick Check:
arrowprops = dict(...) not string [OK]
Hint: arrowprops needs dict, not string like '->' [OK]
Common Mistakes:
Passing arrowprops as string instead of dict
Confusing axhspan with axvspan usage
Thinking xytext must be inside plot limits
5. You want to highlight the time period between 10 and 15 seconds on a line plot and annotate the highest point in that range with a label 'Max'. Which code snippet correctly achieves this?