import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle
from matplotlib.patheffects import withStroke
from matplotlib.ticker import AutoMinorLocator, MultipleLocator
= [0, 20/256, 82/256]
royal_blue
# make the figure
19680801)
np.random.seed(
= np.linspace(0.5, 3.5, 100)
X = 3+np.cos(X)
Y1 = 1+np.cos(1+X/0.75)/2
Y2 = np.random.uniform(Y1, Y2, len(X))
Y3
= plt.figure(figsize=(7.5, 7.5))
fig = fig.add_axes([0.2, 0.17, 0.68, 0.7], aspect=1)
ax
1.000))
ax.xaxis.set_major_locator(MultipleLocator(4))
ax.xaxis.set_minor_locator(AutoMinorLocator(1.000))
ax.yaxis.set_major_locator(MultipleLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator("{x:.2f}")
ax.xaxis.set_minor_formatter(
0, 4)
ax.set_xlim(0, 4)
ax.set_ylim(
='major', width=1.0, length=10, labelsize=14)
ax.tick_params(which='minor', width=1.0, length=5, labelsize=10,
ax.tick_params(which='0.25')
labelcolor
="--", linewidth=0.5, color='.25', zorder=-10)
ax.grid(linestyle
='C0', lw=2.5, label="Blue signal", zorder=10)
ax.plot(X, Y1, c='C1', lw=2.5, label="Orange signal")
ax.plot(X, Y2, c3], Y3[::3], linewidth=0, markersize=9,
ax.plot(X[::='s', markerfacecolor='none', markeredgecolor='C4',
marker=2.5)
markeredgewidth
"Anatomy of a figure", fontsize=20, verticalalignment='bottom')
ax.set_title("x Axis label", fontsize=14)
ax.set_xlabel("y Axis label", fontsize=14)
ax.set_ylabel(="upper right", fontsize=14)
ax.legend(loc
# Annotate the figure
def annotate(x, y, text, code):
# Circle marker
= Circle((x, y), radius=0.15, clip_on=False, zorder=10, linewidth=2.5,
c =royal_blue + [0.6], facecolor='none',
edgecolor=[withStroke(linewidth=7, foreground='white')])
path_effects
ax.add_artist(c)
# use path_effects as a background for the texts
# draw the path_effects and the colored text separately so that the
# path_effects cannot clip other texts
for path_effects in [[withStroke(linewidth=7, foreground='white')], []]:
= 'white' if path_effects else royal_blue
color -0.2, text, zorder=100,
ax.text(x, y='center', va='top', weight='bold', color=color,
ha='italic', fontfamily='monospace',
style=path_effects)
path_effects
= 'white' if path_effects else 'black'
color -0.33, code, zorder=100,
ax.text(x, y='center', va='top', weight='normal', color=color,
ha='monospace', fontsize='medium',
fontfamily=path_effects)
path_effects
3.5, -0.13, "Minor tick label", "ax.xaxis.set_minor_formatter")
annotate(-0.03, 1.0, "Major tick", "ax.yaxis.set_major_locator")
annotate(0.00, 3.75, "Minor tick", "ax.yaxis.set_minor_locator")
annotate(-0.15, 3.00, "Major tick label", "ax.yaxis.set_major_formatter")
annotate(1.68, -0.39, "xlabel", "ax.set_xlabel")
annotate(-0.38, 1.67, "ylabel", "ax.set_ylabel")
annotate(1.52, 4.15, "Title", "ax.set_title")
annotate(1.75, 2.80, "Line", "ax.plot")
annotate(2.25, 1.54, "Markers", "ax.scatter")
annotate(3.00, 3.00, "Grid", "ax.grid")
annotate(3.60, 3.58, "Legend", "ax.legend")
annotate(2.5, 0.55, "Axes", "fig.subplots")
annotate(4, 4.5, "Figure", "plt.figure")
annotate(0.65, 0.01, "x Axis", "ax.xaxis")
annotate(0, 0.36, "y Axis", "ax.yaxis")
annotate(4.0, 0.7, "Spine", "ax.spines")
annotate(
# frame around figure
set(linewidth=4, edgecolor='0.5')
fig.patch. plt.show()
21 Anatomía de una gráfica
En esta sección exploraremos la anatomía de las figuras en Matplotlib, un conocimiento fundamental para cualquier persona que se dedique a la visualización de datos. Descubriremos los componentes básicos de una figura para construir visualizaciones claras y efectivas.
Conocer la anatomía de una figura en Matplotlib es como aprender la gramática antes de escribir una novela; es el primer paso para dominar el arte de la visualización de datos. Desde los ‘Axes’ hasta los ‘Ticks’, cada parte de una figura desempeña un papel crucial en la creación y personalización de gráficos que se ajusten a nuestras necesidades específicas de análisis y formato.