As we just saw, adding annotations is relatively simple: we can use plt.annotate()
, and pass in parameters for text
and (xy)
position. To recap:
plt.annotate(‘Look at this point!’, (15, 35))
plt.annotate()
also takes many more parameters for more detailed annotations, including:
fontsize
andcolor
ha
andva
to set horizontal and vertical alignmentbackgroundcolor
We can also use plt.annotate()
to add arrows to a graph, with the following parameters:
arrowprops
to style an arrow from the annotation to a pointxytext
to reposition the text, if an arrow is used – the arrowhead will automatically be positioned at(xy)
Heads up: arrowprops
is a dictionary of parameters – so we’ll actually end up with a list of arrowprops
parameters nested inside our list of plt.annotate
parameters.
plt.annotate('Look at this point!', xy=(15, 35), xytext=(17, 40), fontsize=14, color='blue', arrowprops=dict(arrowstyle= '-|-|>', color='blue'))
In this exercise, we’ll further improve our species count graph by using annotations to highlight a few tree genuses of interest.
Instructions
Now, let’s add annotations to highlight the Banara
genus, which occupies a dramatically different position in each type of forest. We’ll do the annotation here, and add an arrow in the next step. Make an annotation of 'Banara'
on each graph, with font size of 14 and the color 'royalblue'
to match the Banara bar color. Set the xy
value for Primary Forest
to (77, 3)
. Set xy
value for Secondary Forest
to (3.5, 48)
. Set the xy
value for Selectively Logged Forest
to (33, 5)
.
Let’s add arrows to these labels. Within the arrowprops
dict
, set the arrowstyle
to '-|>'
for a solid-line arrow. Set the color
to royalblue
to match the annotation. Once we add an arrow property, the arrowhead will automatically be placed at the xy
position we just set. To re-set the text at the proper position, we set it an xytext
value. Set the xytext
value for Primary Forest
to (75, 20)
. Set xytext
value for Secondary Forest
to (8, 60)
. Set the xytext
value for Selectively Logged Forest
to (31, 20)
.