Introdução
Matplotlib é uma biblioteca de plotagem para a linguagem de programação Python e sua extensão de matemática numérica NumPy. Este tutorial focará no alinhamento de texto em Matplotlib.
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ê.
Criando um Retângulo
Começaremos criando um retângulo no gráfico usando a função Rectangle() do módulo matplotlib.patches. Após criar o retângulo, definiremos seus limites horizontal e vertical usando as funções set_xlim() e set_ylim(). Finalmente, adicionaremos o retângulo ao gráfico.
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
fig, ax = plt.subplots()
## Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
p = Rectangle((left, bottom), width, height, fill=False)
ax.add_patch(p)
## Set the horizontal and vertical limits
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()
Adicionando Texto ao Retângulo
Nesta etapa, adicionaremos texto ao retângulo usando a função text(). O alinhamento horizontal e vertical do texto será definido usando os parâmetros horizontalalignment e verticalalignment, respectivamente.
## Add text to the rectangle
ax.text(left, bottom, 'left top',
horizontalalignment='left',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, bottom, 'left bottom',
horizontalalignment='left',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right bottom',
horizontalalignment='right',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right top',
horizontalalignment='right',
verticalalignment='top',
transform=ax.transAxes)
ax.text(right, bottom, 'center top',
horizontalalignment='center',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'right center',
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'left center',
horizontalalignment='left',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
horizontalalignment='center',
verticalalignment='center',
transform=ax.transAxes)
ax.text(right, 0.5 * (bottom + top), 'centered',
horizontalalignment='center',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, top, 'rotated\nwith newlines',
horizontalalignment='center',
verticalalignment='center',
rotation=45,
transform=ax.transAxes)
plt.show()
Personalizando o Gráfico
Nesta etapa, personalizaremos o gráfico adicionando rótulos aos eixos e removendo as linhas dos eixos.
## Customize the plot
ax.set_axis_off()
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_title('Text Alignment in Matplotlib')
plt.show()
Resumo
Neste tutorial, aprendemos como alinhar texto em Matplotlib. Usamos a função text() para adicionar texto a um retângulo e definimos o alinhamento horizontal e vertical usando os parâmetros horizontalalignment e verticalalignment, respectivamente. Também personalizamos o gráfico adicionando rótulos aos eixos e removendo as linhas dos eixos.