Subplots en Matplotlib: A Complete Guide
Matplotlib es una de las bibliotecas más populares en Python para la creación de gráficos y visualizaciones de datos. Con su extensa funcionalidad, permite a los analistas y científicos de datos crear visualizaciones atractivas y significativas. One of the most useful concepts in Matplotlib is subplots. In this article, we will explore how to use subplots in Matplotlib, Your advantages, and provide practical examples so you can make the most of this tool.
What are Subplots?
Subplots are a way to organize multiple plots into one figure"Figure" is a term that is used in various contexts, From art to anatomy. In the artistic field, refers to the representation of human or animal forms in sculptures and paintings. In anatomy, designates the shape and structure of the body. What's more, in mathematics, "figure" it is related to geometric shapes. Its versatility makes it a fundamental concept in multiple disciplines.... in Matplotlib. This is especially useful when you want to compare different datasets or when you need to display different variables in the same visual setting. Using subplots can help you tell a more complete story with your data, making it easier for the viewer to understand.
Advantages of Using Subplots
- Comparación Visual: They allow you to compare different plots side by side, making it easier to identify patterns, tendencias y correlaciones.
- Space Efficiency: Ayudan a maximizar el uso del espacio en una figura, permitiendo que se muestren múltiples visualizaciones sin necesidad de abrir varias ventanas.
- Organization: Mantienen tus gráficos organizados y bien presentados, lo que es especialmente importante en informes y presentaciones.
- Consistency: Al usar el mismo estilo y formato en múltiples subplots, se asegura una presentación visual consistente.
Creando Subplots en Matplotlib
Para crear subplots en Matplotlib, utilizamos la función plt.subplots(). Esta función nos permite definir la cantidad de filas y columnas en las que queremos dividir nuestra figura. Then, veremos la sintaxis básica y algunos ejemplos prácticos.
Basic Syntax
import matplotlib.pyplot as plt
fig, axs = plt.subplots(nrows, ncols)
nrows: Número de filas de subplots.ncols: Número de columnas de subplots.fig: Objeto de la figura que contiene todos los subplots.axs: Un arreglo de ejes de subplots.
Example 1: Subplots Simples
Veamos un ejemplo simple en el que creamos una figura con 2 rows and 2 columnas de subplots.
import matplotlib.pyplot as plt
import numpy as np
# Datos de ejemplo
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.exp(x)
# Crear subplots
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
# Gráficos
axs[0, 0].plot(x, y1, 'r')
axs[0, 0].set_title('Seno')
axs[0, 1].plot(x, y2, 'g')
axs[0, 1].set_title('Coseno')
axs[1, 0].plot(x, y3, 'b')
axs[1, 0].set_title('Tangente')
axs[1, 1].plot(x, y4, 'm')
axs[1, 1].set_title('Exponencial')
# Ajustar espacio
plt.tight_layout()
plt.show()
In this example, hemos creado una figura con cuatro subplots, cada uno mostrando diferentes funciones matemáticas. The function plt.tight_layout() se utiliza aquí para ajustar automáticamente los espacios entre los subplots y mejorar la presentación.
Example 2: Subplots con Diferentes Tipos de Gráficos
Sometimes, es útil mostrar diferentes tipos de gráficos en un solo conjunto de subplots. Let's see how to do this.
import matplotlib.pyplot as plt
import numpy as np
# Datos de ejemplo
x = np.linspace(0, 10, 100)
y = np.random.rand(100)
# Crear subplots
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
# Gráfico de líneas
axs[0, 0].plot(x, np.sin(x), color='r')
axs[0, 0].set_title('Gráfico de Línea')
# Gráfico de dispersión
axs[0, 1].scatter(x, y, color='g')
axs[0, 1].set_title('Gráfico de Dispersión')
# Histograma
axs[1, 0].hist(y, bins=10, color='b')
axs[1, 0].set_title('Histograma')
# Gráfico de barras
axs[1, 1].bar(np.arange(len(y)), y, color='m')
axs[1, 1].set_title('Gráfico de Barras')
# Ajustar espacio
plt.tight_layout()
plt.show()
Aquí hemos combinado un gráfico de línea, a scatter plotA scatter plot is a visual representation that shows the relationship between two numerical variables using points on a Cartesian plane. Each axis represents a variable, and the location of each point indicates its value in relation to both. This type of chart is useful for identifying patterns, Correlations and trends in the data, facilitating the analysis and interpretation of quantitative relationships...., un histograma y un bar graphicThe bar chart is a visual representation of data that uses rectangular bars to show comparisons between different categories. Each bar represents a value and its length is proportional to it. This type of chart is useful for visualizing and analyzing trends, facilitating the interpretation of quantitative information. It is widely used in various disciplines, such as statistics, Marketing and research, due to its simplicity and effectiveness.... en un solo conjunto de subplots. Esto demuestra la flexibilidad que ofrece Matplotlib para personalizar tus visualizaciones.
Personalizando Subplots
Cambiando el Tamaño de los Subplots
Puedes cambiar el Figure sizeThe "Figure size" refers to the dimensions and proportions of an object or representation in the field of art, Design and Anatomy. This concept is fundamental to visual composition, since it influences the perception and impact of the work. Understanding the right size allows you to create aesthetic balance and visual hierarchy, thus facilitating the effective communication of the desired message.... al crear los subplots utilizando el argumento figsize:
fig, axs = plt.subplots(2, 2, figsize=(12, 10))
Títulos y Etiquetas
Los títulos y las etiquetas son cruciales para la comprensión de tus gráficos. Puedes agregar títulos y etiquetas a los ejes de la siguiente manera:
axs[0, 0].set_title('Título del Gráfico')
axs[0, 0].set_xlabel('Eje X')
axs[0, 0].set_ylabel('Eje Y')
Leyendas
Si tienes múltiples líneas o datos en un subplot, es posible que desees agregar una leyenda para mayor claridad:
axs[0, 0].plot(x, y1, label='Seno', color='r')
axs[0, 0].plot(x, y2, label='Coseno', color='g')
axs[0, 0].legend()
Ajustando el Espacio entre Subplots
Sometimes, los subplots pueden estar muy juntos o superponerse. Puedes ajustar el espacio utilizando:
plt.tight_layout(): ajusta automáticamente el espacio.plt.subplots_adjust(): permite un control más detallado sobre el espacio entre los subplots.
plt.subplots_adjust(hspace=0.4, wspace=0.4)
Ejemplo Avanzado: Subplots con Diferentes Escalas
En algunos análisis, puede ser útil mostrar diferentes escalas en los subplots. Veamos un ejemplo donde utilizamos escalas logarítmicas.
import matplotlib.pyplot as plt
import numpy as np
# Datos
x = np.linspace(1, 100, 100)
y1 = np.log(x)
y2 = np.exp(x)
# Crear subplots
fig, axs = plt.subplots(2, 1, figsize=(10, 8))
# Gráfico Logarítmico
axs[0].plot(x, y1, label='Logarítmico', color='b')
axs[0].set_title('Escala Logarítmica')
axs[0].set_yscale('log')
axs[0].legend()
# Gráfico Exponencial
axs[1].plot(x, y2, label='Exponencial', color='r')
axs[1].set_title('Escala Exponencial')
axs[1].set_yscale('linear')
axs[1].legend()
# Ajustar espacio
plt.tight_layout()
plt.show()
In this example, we have used logarithmic and linear scales in different subplots to compare how logarithmic and exponential functions behave.
FAQ about Subplots in Matplotlib
1. How can I create subplots with different sizes?
You can create subplots with different sizes using the function GridSpec from Matplotlib. This allows you to specify the size ratio of each subplot.
2. What should I do if my subplots overlap?
Used plt.tight_layout() to automatically adjust the spacing between subplots. If you need more detailed control, you can use plt.subplots_adjust() to manually specify the spacing.
3. Can I add an overall title to all subplots?
Yes, puedes utilizar fig.suptitle('Título General') to add a title that spans the entire figure.
4. How can I save my plots with subplots?
You can save your plots using plt.savefig('nombre_del_archivo.png') before calling plt.show(). Make sure to do it in the format you want (PNG, JPG, etc.).
5. Is it possible to have subplots in different figures?
No, each set of subplots you create with plt.subplots() belongs to the same figure. But nevertheless, you can create multiple figures using fig = plt.figure() O plt.figure() for separate plots.
6. How can I change the background color of a subplot?
You can change the background color of a subplot using axs[i, j].set_facecolor('color') where 'color'’ can be a color name, hex code, etc.
Conclution
Subplots are a powerful tool in Matplotlib that allow you to organize and present multiple data visualizations effectively. A lo largo de este artículo, we have explored how to create, customize and adjust subplots, providing practical examples so you can implement them in your own work. By mastering the use of subplots, mejorarás tus habilidades en la visualización de datos y podrás presentar tus análisis de una manera más clara y comprensible. ¡Empieza a experimentar con subplots y transforma tus visualizaciones hoy mismo!



