Tutorial de visualización con Pcolor en Matplotlib

PythonPythonBeginner
Practicar Ahora

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

💡 Este tutorial está traducido por IA desde la versión en inglés. Para ver la versión original, puedes hacer clic aquí

Introducción

Este tutorial es una introducción al uso de Pcolor en Matplotlib. Pcolor te permite generar gráficos en estilo de imagen 2D, y te mostraremos cómo usarlo en Matplotlib.

Consejos sobre la VM

Una vez que se haya completado la inicialización de la VM, haz clic en la esquina superior izquierda para cambiar a la pestaña Cuaderno y acceder a Jupyter Notebook para practicar.

A veces, es posible que tengas que esperar unos segundos a que Jupyter Notebook termine de cargarse. La validación de las operaciones no se puede automatizar debido a las limitaciones de Jupyter Notebook.

Si tienes problemas durante el aprendizaje, no dudes en preguntar a Labby. Proporciona retroalimentación después de la sesión y te resolveremos el problema inmediatamente.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) matplotlib(("Matplotlib")) -.-> matplotlib/PlottingDataGroup(["Plotting Data"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/for_loops("For Loops") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("Heatmaps") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/FileHandlingGroup -.-> python/with_statement("Using with Statement") python/PythonStandardLibraryGroup -.-> python/math_random("Math and Random") subgraph Lab Skills python/comments -.-> lab-48858{{"Tutorial de visualización con Pcolor en Matplotlib"}} python/for_loops -.-> lab-48858{{"Tutorial de visualización con Pcolor en Matplotlib"}} matplotlib/heatmaps -.-> lab-48858{{"Tutorial de visualización con Pcolor en Matplotlib"}} python/lists -.-> lab-48858{{"Tutorial de visualización con Pcolor en Matplotlib"}} python/tuples -.-> lab-48858{{"Tutorial de visualización con Pcolor en Matplotlib"}} python/build_in_functions -.-> lab-48858{{"Tutorial de visualización con Pcolor en Matplotlib"}} python/standard_libraries -.-> lab-48858{{"Tutorial de visualización con Pcolor en Matplotlib"}} python/with_statement -.-> lab-48858{{"Tutorial de visualización con Pcolor en Matplotlib"}} python/math_random -.-> lab-48858{{"Tutorial de visualización con Pcolor en Matplotlib"}} end

Simple Pcolor Demo

El primer paso es crear una demostración simple de Pcolor. Esto te mostrará cómo crear un gráfico básico de Pcolor.

Z = np.random.rand(6, 10)

fig, (ax0, ax1) = plt.subplots(2, 1)

c = ax0.pcolor(Z)
ax0.set_title('default: no edges')

c = ax1.pcolor(Z, edgecolors='k', linewidths=4)
ax1.set_title('thick edges')

fig.tight_layout()
plt.show()

Comparing Pcolor with Similar Functions

El segundo paso es comparar Pcolor con funciones similares, como Pcolormesh, Imshow y Pcolorfast. Esto te ayudará a entender las diferencias entre estas funciones y cuándo utilizar cada una.

## make these smaller to increase the resolution
dx, dy = 0.15, 0.05

## generate 2 2d grids for the x & y bounds
y, x = np.mgrid[-3:3+dy:dy, -3:3+dx:dx]
z = (1 - x/2 + x**5 + y**3) * np.exp(-x**2 - y**2)
## x and y are bounds, so z should be the value *inside* those bounds.
## Therefore, remove the last value from the z array.
z = z[:-1, :-1]
z_min, z_max = -abs(z).max(), abs(z).max()

fig, axs = plt.subplots(2, 2)

ax = axs[0, 0]
c = ax.pcolor(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolor')
fig.colorbar(c, ax=ax)

ax = axs[0, 1]
c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolormesh')
fig.colorbar(c, ax=ax)

ax = axs[1, 0]
c = ax.imshow(z, cmap='RdBu', vmin=z_min, vmax=z_max,
              extent=[x.min(), x.max(), y.min(), y.max()],
              interpolation='nearest', origin='lower', aspect='auto')
ax.set_title('image (nearest, aspect="auto")')
fig.colorbar(c, ax=ax)

ax = axs[1, 1]
c = ax.pcolorfast(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolorfast')
fig.colorbar(c, ax=ax)

fig.tight_layout()
plt.show()

Pcolor with a Log Scale

El tercer paso es crear un gráfico de Pcolor con una escala logarítmica. Esto es útil cuando tienes datos con una amplia gama de valores.

N = 100
X, Y = np.meshgrid(np.linspace(-3, 3, N), np.linspace(-2, 2, N))

## A low hump with a spike coming out.
## Needs to have z/colour axis on a log scale, so we see both hump and spike.
## A linear scale only shows the spike.
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
Z = Z1 + 50 * Z2

fig, (ax0, ax1) = plt.subplots(2, 1)

c = ax0.pcolor(X, Y, Z, shading='auto',
               norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r')
fig.colorbar(c, ax=ax0)

c = ax1.pcolor(X, Y, Z, cmap='PuBu_r', shading='auto')
fig.colorbar(c, ax=ax1)

plt.show()

Resumen

Este tutorial te ha mostrado cómo usar Pcolor en Matplotlib. Empezamos con una demostración simple de Pcolor, luego comparamos Pcolor con funciones similares como Pcolormesh e Imshow. Finalmente, creamos un gráfico de Pcolor con una escala logarítmica.