Anotar Figuras com AnnotationBbox

Beginner

This tutorial is from open-source community. Access the source code

Introdução

Neste laboratório, aprenderemos como usar AnnotationBbox no Matplotlib para anotar figuras usando texto, formas e imagens. AnnotationBbox é um método de controle mais detalhado do que Axes.annotate. Passaremos por três diferentes OffsetBoxes: TextArea, DrawingArea e OffsetImage.

Dicas para a VM

Após a inicialização da VM, clique no canto superior esquerdo para mudar para a aba Notebook e acessar o Jupyter Notebook para praticar.

Às vezes, pode ser necessário aguardar alguns segundos para que o Jupyter Notebook termine de carregar. A validação das operações não pode ser automatizada devido às limitações do Jupyter Notebook.

Se você enfrentar problemas durante o aprendizado, sinta-se à vontade para perguntar ao Labby. Forneça feedback após a sessão, e resolveremos o problema prontamente para você.

Plotando Pontos

Para começar, vamos plotar dois pontos que anotaremos mais tarde.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

## Define a 1st position to annotate (display it with a marker)
xy1 = (0.5, 0.7)
ax.plot(xy1[0], xy1[1], ".r")

## Define a 2nd position to annotate (don't display with a marker this time)
xy2 = [0.3, 0.55]

## Fix the display limits to see everything
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

plt.show()

Anotando com TextArea

Agora, vamos anotar o primeiro ponto usando um TextArea.

from matplotlib.offsetbox import AnnotationBbox, TextArea

## Annotate the 1st position with a text box ('Test 1')
offsetbox = TextArea("Test 1")

ab = AnnotationBbox(offsetbox, xy1,
                    xybox=(-20, 40),
                    xycoords='data',
                    boxcoords="offset points",
                    arrowprops=dict(arrowstyle="->"),
                    bboxprops=dict(boxstyle="sawtooth"))

ax.add_artist(ab)

plt.show()

Anotando com DrawingArea

Em seguida, vamos anotar o segundo ponto com um patch de círculo usando DrawingArea.

from matplotlib.offsetbox import DrawingArea
from matplotlib.patches import Circle

## Annotate the 2nd position with a circle patch
da = DrawingArea(20, 20, 0, 0)
p = Circle((10, 10), 10)
da.add_artist(p)

ab = AnnotationBbox(da, xy2,
                    xybox=(1., xy2[1]),
                    xycoords='data',
                    boxcoords=("axes fraction", "data"),
                    box_alignment=(0.2, 0.5),
                    arrowprops=dict(arrowstyle="->"),
                    bboxprops=dict(alpha=0.5))

ax.add_artist(ab)

plt.show()

Anotando com OffsetImage

Finalmente, vamos anotar o segundo ponto com um OffsetImage usando uma imagem de Grace Hopper.

from matplotlib.cbook import get_sample_data
from matplotlib.offsetbox import OffsetImage

## Annotate the 2nd position with an image (a generated array of pixels)
arr = np.arange(100).reshape((10, 10))
im = OffsetImage(arr, zoom=2)
im.image.axes = ax

ab = AnnotationBbox(im, xy2,
                    xybox=(-50., 50.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.3,
                    arrowprops=dict(arrowstyle="->"))

ax.add_artist(ab)

## Annotate the 2nd position with another image (a Grace Hopper portrait)
with get_sample_data("grace_hopper.jpg") as file:
    arr_img = plt.imread(file)

imagebox = OffsetImage(arr_img, zoom=0.2)
imagebox.image.axes = ax

ab = AnnotationBbox(imagebox, xy2,
                    xybox=(120., -80.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.5,
                    arrowprops=dict(
                        arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=3")
                    )

ax.add_artist(ab)

plt.show()

Resumo

Neste laboratório, aprendemos como usar AnnotationBbox no Matplotlib para anotar figuras usando texto, formas e imagens. Passamos por três diferentes OffsetBoxes: TextArea, DrawingArea e OffsetImage. Ao usar AnnotationBbox, temos um controle mais preciso sobre as anotações do que usando Axes.annotate.