Introdução
Matplotlib é uma popular biblioteca Python utilizada para criar visualizações, incluindo gráficos e diagramas. Um dos componentes chave do Matplotlib são os marcadores (markers), que são usados para representar pontos de dados em um gráfico. Os marcadores vêm em várias formas, tamanhos e estilos, e podem ser personalizados para se adequar a um conjunto de dados específico. Neste laboratório, você aprenderá como usar marcadores do Matplotlib para criar visualizações personalizadas que comunicam seus dados de forma eficaz.
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 a limitações no 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ê.
Marcadores Não Preenchidos (Unfilled Markers)
Marcadores não preenchidos são de cor única. O código a seguir demonstra como criar marcadores não preenchidos:
unfilled_markers = [m for m, func in Line2D.markers.items()
if func != 'nothing' and m not in Line2D.filled_markers]
for ax, markers in zip(axs, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
Marcadores Preenchidos (Filled Markers)
Marcadores preenchidos são o oposto de marcadores não preenchidos. O código a seguir demonstra como criar marcadores preenchidos:
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
Estilos de Preenchimento de Marcadores (Marker Fill Styles)
A cor da borda e a cor de preenchimento de marcadores preenchidos podem ser especificadas separadamente. Adicionalmente, o fillstyle pode ser configurado para ser não preenchido (unfilled), totalmente preenchido (fully filled) ou semi-preenchido (half-filled) em várias direções. Os estilos semi-preenchidos usam markerfacecoloralt como uma cor de preenchimento secundária. O código a seguir demonstra como criar estilos de preenchimento de marcadores:
fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
color='darkgrey',
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown')
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style), **text_style)
ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
Marcadores Criados a partir de Símbolos TeX
Use :ref:MathText <mathtext> para usar símbolos de marcador personalizados, como por exemplo, "$\u266B$". Para uma visão geral dos símbolos da fonte STIX, consulte a tabela de fontes STIX <http://www.stixfonts.org/allGlyphs.html>_. Veja também o :doc:/gallery/text_labels_and_annotations/stix_fonts_demo.
fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)
marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$", r"$\mathcal{A}$"]
for y, marker in enumerate(markers):
## Escape dollars so that the text is written "as is", not as mathtext.
ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
Marcadores Criados a partir de Caminhos (Paths)
Qualquer ~.path.Path pode ser usado como um marcador. O exemplo a seguir mostra dois caminhos simples star (estrela) e circle (círculo), e um caminho mais elaborado de um círculo com uma estrela recortada.
import numpy as np
import matplotlib.path as mpath
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
## concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
codes=np.concatenate([circle.codes, star.codes]))
fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)
markers = {'star': star, 'circle': circle, 'cut_star': cut_star}
for y, (name, marker) in enumerate(markers.items()):
ax.text(-0.5, y, name, **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
Modificações Avançadas de Marcadores com Transformação (Transform)
Os marcadores podem ser modificados passando uma transformação (transform) para o construtor MarkerStyle. O exemplo a seguir mostra como uma rotação fornecida é aplicada a várias formas de marcador.
common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]
fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)
ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)
ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)
ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
eq = r'$\frac{1}{x}$'
ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)
for x, theta in enumerate(angles):
ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)
fig.tight_layout()
Definindo o Estilo de Extremidade (Cap Style) e o Estilo de Junção (Join Style) do Marcador
Os marcadores têm estilos de extremidade (cap) e junção (join) padrão, mas estes podem ser personalizados ao criar um MarkerStyle.
from matplotlib.markers import CapStyle, JoinStyle
marker_inner = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown',
markeredgewidth=8,
)
marker_outer = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='white',
markeredgewidth=1,
)
fig, ax = plt.subplots()
fig.suptitle('Marker CapStyle', fontsize=14)
fig.subplots_adjust(left=0.1)
for y, cap_style in enumerate(CapStyle):
ax.text(-0.5, y, cap_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('1', transform=t, capstyle=cap_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.plot(x, y, marker=m, **marker_outer)
ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
Modificando o Estilo de Junção (Join Style)
O estilo de junção (join style) dos marcadores também pode ser modificado de maneira semelhante.
fig, ax = plt.subplots()
fig.suptitle('Marker JoinStyle', fontsize=14)
fig.subplots_adjust(left=0.05)
for y, join_style in enumerate(JoinStyle):
ax.text(-0.5, y, join_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('*', transform=t, joinstyle=join_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.text(x, len(JoinStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
plt.show()
Resumo
Neste laboratório, você aprendeu como usar marcadores do Matplotlib para criar visualizações personalizadas. Especificamente, você aprendeu como criar marcadores não preenchidos e preenchidos, estilos de preenchimento de marcadores, marcadores criados a partir de símbolos TeX, marcadores criados a partir de caminhos, modificações avançadas de marcadores com transformações (transform) e como definir o estilo de extremidade (cap style) e o estilo de junção (join style) do marcador. Ao usar essas técnicas, você pode criar visualizações eficazes que comunicam seus dados com clareza e precisão.