Una figura, un Axes, una línea
Un gráfico es la forma más rápida de ver que una serie de precios está limpia, con tendencia o rota. En matplotlib una Figure es todo el lienzo y un Axes es un gráfico sobre él, con sus líneas, etiquetas y leyenda. La forma orientada a objetos es fig, ax = plt.subplots() seguido de llamadas sobre ax: ax.plot(x, y) dibuja una línea, ax.set_title, ax.set_xlabel y ax.set_ylabel nombran el gráfico. Dibujar en un Axes explícito y devolverlo hace que una función de dibujo sea fácil de reutilizar y de probar.
import matplotlib
matplotlib.use("Agg") # draw without a window (no screen needed)
import matplotlib.pyplot as plt
import pandas as pd
prices = pd.Series([100.0, 102, 101, 105, 107, 106, 110], index=pd.bdate_range("2026-03-02", periods=7))
fig, ax = plt.subplots()
ax.plot(prices.index, prices.values, label="AAPL")
ax.set_title("Closing price")
ax.set_xlabel("Date")
ax.set_ylabel("Price (USD)")
print(ax.get_title(), "|", ax.get_xlabel(), "|", ax.get_ylabel()) # Closing price | Date | Price (USD)
print(len(ax.lines), ax.lines[0].get_ydata().tolist()) # 1 [100.0, 102.0, 101.0, 105.0, 107.0, 106.0, 110.0]Etiquetas y leyenda
Con varias líneas en un gráfico, cada una necesita un nombre. Pasa label="..." a ax.plot y llama a ax.legend() una vez al final: la leyenda lista las etiquetas en el orden en que se dibujaron las líneas. Un gráfico sin etiquetas, título y unidades es una imagen, no un resultado. Las líneas también tienen estilo: linestyle="--" da una línea discontinua, útil para una media que no debe tapar los precios, y color, linewidth y marker lo afinan más.
ma = prices.rolling(3).mean()
ax.plot(ma.index, ma.values, label="MA3", linestyle="--")
ax.legend()
print([line.get_label() for line in ax.lines]) # ['AAPL', 'MA3']
print([text.get_text() for text in ax.get_legend().get_texts()]) # ['AAPL', 'MA3']
print(ax.lines[1].get_linestyle(), ax.lines[1].get_ydata().tolist()[:3]) # -- [nan, nan, 101.0] NaN points are simply not drawnLíneas de referencia y gráficos que no puedes ver
Una línea horizontal marca un nivel como un strike, un stop o la media: ax.axhline(105, linestyle="--") la dibuja a lo ancho de todo el gráfico (axvline hace lo mismo en vertical). Matplotlib también puede dibujar sin ninguna ventana: con el backend Agg, fig.savefig("chart.png") escribe el gráfico en un archivo, que es como los informes y servidores producen gráficos. Como todo lo que dibujas queda en el objeto Axes, un programa (o una prueba) puede leerlo de vuelta: las líneas con ax.lines, sus datos con get_ydata(), las etiquetas con get_label(), el título con get_title().
ax.axhline(105, linestyle=":", label="level")
level_line = ax.lines[-1]
print(list(level_line.get_ydata()), level_line.get_linestyle(), level_line.get_label()) # [105, 105] : level
fig.savefig("prices.png") # writes the chart to a file; no window, no plt.show() needed
plt.close(fig) # release the figure when you are done with itdef plot_prices(prices):
fig, ax = plt.subplots()
ax.plot(prices.index, prices.values)
ax.set_title("Closing price")
return ax # the caller can add lines, save the chart or inspect it
ax = plot_prices(prices)
print(len(ax.lines), ax.get_title()) # 1 Closing price
plt.close("all")plt.subplots() mantiene su figura en memoria hasta que llamas a plt.close(fig). En un bucle que dibuja cientos de gráficos, o en un servidor, olvidarlo pierde memoria y acaba lanzando una advertencia. Crea la Figure dentro de la función, devuelve lo que necesite quien llama y deja que este la cierre.fig, ax = plt.subplots()y luegoax.plot(x, y); nombra el gráfico conset_title,set_xlabelyset_ylabel.- Da un
label=a cada línea y llama aax.legend();linestyle="--"dibuja una línea discontinua;ax.axhline(y)una horizontal. - Dibuja en un Axes y devuélvelo:
ax.lines,get_ydata()yget_label()leen el gráfico; usasavefigyplt.closeen lugar deshowen los programas.
A continuación: los gráficos de velas, para dibujar apertura, máximo, mínimo y cierre de cada día.
Lab: qué se califica
- Dibujar la línea de precios con
plot_prices25 pts - Comparar dos series en un gráfico con
plot_comparison25 pts - Añadir una media móvil discontinua con
plot_with_average25 pts - Marcar un nivel de precio con
plot_with_level25 pts