Annotating graphs
It is often convenient to annotate plots to indicate relevant features, or to add text with commentary to the graph. Matplotlib provides two main functions to add these features to a plot:
annotate()
creates an annotation associated to a specific point in a graph, with an optional arrow pointing to the relevant valuetext()
adds generic text to a graph
The next recipe shows how to add the two kinds of annotation.
Getting ready
Start Jupyter and run the following three commands in an execution cell:
%matplotlib inline import numpy as np import matplotlib.pyplot as plt
How to do it…
Run the following code in an execution cell:
from scipy.stats import gamma distr = gamma(2.0) xvalues = np.linspace(0, 10, 100) yvalues = distr.pdf(xvalues) plt.plot(xvalues, yvalues, color='orange') plt.title('Mean and median') plt.xlabel('$x$') plt.ylabel('$f(x)$') xmean = distr.mean() ymean = distr.pdf(xmean) xmed = distr.median() ymed = distr.pdf(xmed) aprops = dict(arrowstyle = '->') plt.annotate...