GOOGLE ADS

viernes, 22 de abril de 2022

Bucle en Matplotlib en una sola subparcela

Actualmente estoy trabajando en el análisis de componentes principales y me gustaría trazar un círculo de correlación, 3 en mi caso porque tengo 3 PCA.

El código está bien, pero me gustaría mostrar el resultado en una subparcela (1 fila, 3 columnas) porque ahora tengo 3 cifras consecutivas.

Cuando trato de iniciar la figura de Matplotlib fig, ax = plt.subplots(1,3), devuelve 3 "cuadrículas" de subparcelas de 1x3 con 1 círculo dentro de cada una. Entonces, en lugar de eso, me gustaría 1 "cuadrícula" con mis 3 círculos en 3 columnas en la misma fila.

Mi código:

pcs = pca.components_
def display_circles(pcs, n_comp, pca, axis_ranks, labels=None, label_rotation=0, lims=None):
# Initialise the matplotlib figure
fig, ax = plt.subplots(1,3)
# For each factorial plane
for d1, d2 in axis_ranks:
if d2 < n_comp:
# Determine the limits of the chart
if lims is not None:
xmin, xmax, ymin, ymax = lims
elif pcs.shape[1] < 30:
xmin, xmax, ymin, ymax = -1, 1, -1, 1
else:
xmin, xmax, ymin, ymax = min(pcs[d1,:]), max(pcs[d1,:]), min(pcs[d2,:]), max(pcs[d2,:])
# Add arrows
plt.quiver(np.zeros(pcs.shape[1]), np.zeros(pcs.shape[1]), pcs[d1,:], pcs[d2,:], angles='xy', scale_units='xy', scale=1, color="grey")

# Display variable names
if labels is not None:
for i,(x, y) in enumerate(pcs[[d1,d2]].T):
if x >= xmin and x <= xmax and y >= ymin and y <= ymax:
plt.text(x, y, labels[i], fontsize='10', ha='center', va='center', rotation=label_rotation, color="blue", alpha=0.5)

# Display circle
circle = plt.Circle((0,0), 1, facecolor='none', edgecolor='b')
plt.gca().add_artist(circle)
# Label the axes, with the percentage of variance explained
plt.xlabel('PC{} ({}%)'.format(d1+1, round(100*pca.explained_variance_ratio_[d1],1)))
plt.ylabel('PC{} ({}%)'.format(d2+1, round(100*pca.explained_variance_ratio_[d2],1)))
plt.title("Correlation Circle (PC{} and PC{})".format(d1+1, d2+1))
plt.show(block=False)
display_circles(pcs, num_components, pca, [(0,1), (1,2), (0,2)], labels = header)

Gracias por la ayuda!!


Solución del problema

Lamentablemente, no proporcionó datos, por lo que esta respuesta solo explicará lo que puede hacer para lograr su objetivo.

Con fig, ax = plt.subplots(1,3)usted creó 3 ejes diferentes que se almacenan en el interior ax. Entonces, ax[0]se refiere al primer eje de la izquierda, ax[1]se refiere al eje central, ax[2]se refiere al eje de la derecha. Los usamos para apuntar al eje correcto.

Como tiene 3 PCA, necesitamos un índice para apuntar al eje correcto. Entonces, cambia for d1, d2 in axis_ranks:a for k, (d1, d2) in enumerate(axis_ranks):. Ahora podemos usar el índice kpara apuntar al eje correcto.

A continuación, debe reemplazar plt.con ax[i].. Sin embargo, debemos tener cuidado, ya que algunos métodos tendrán un nombre diferente:

pcs = pca.components_
def display_circles(pcs, n_comp, pca, axis_ranks, labels=None, label_rotation=0, lims=None):
# Initialise the matplotlib figure
fig, ax = plt.subplots(1,3)
# For each factorial plane
for k, (d1, d2) in enumerate(axis_ranks):
if d2 < n_comp:
# Determine the limits of the chart
if lims is not None:
xmin, xmax, ymin, ymax = lims
elif pcs.shape[1] < 30:
xmin, xmax, ymin, ymax = -1, 1, -1, 1
else:
xmin, xmax, ymin, ymax = min(pcs[d1,:]), max(pcs[d1,:]), min(pcs[d2,:]), max(pcs[d2,:])
# Add arrows
ax[k].quiver(np.zeros(pcs.shape[1]), np.zeros(pcs.shape[1]), pcs[d1,:], pcs[d2,:], angles='xy', scale_units='xy', scale=1, color="grey")

# Display variable names
if labels is not None:
for i,(x, y) in enumerate(pcs[[d1,d2]].T):
if x >= xmin and x <= xmax and y >= ymin and y <= ymax:
ax[k].text(x, y, labels[i], fontsize='10', ha='center', va='center', rotation=label_rotation, color="blue", alpha=0.5)

# Display circle
circle = plt.Circle((0,0), 1, facecolor='none', edgecolor='b')
ax[k].add_artist(circle)
# Label the axes, with the percentage of variance explained
ax[k].set_xlabel('PC{} ({}%)'.format(d1+1, round(100*pca.explained_variance_ratio_[d1],1)))
ax[k].set_ylabel('PC{} ({}%)'.format(d2+1, round(100*pca.explained_variance_ratio_[d2],1)))
ax[k].set_title("Correlation Circle (PC{} and PC{})".format(d1+1, d2+1))
display_circles(pcs, num_components, pca, [(0,1), (1,2), (0,2)], labels = header)

No hay comentarios.:

Publicar un comentario

Flutter: error de rango al acceder a la respuesta JSON

Estoy accediendo a una respuesta JSON con la siguiente estructura. { "fullName": "FirstName LastName", "listings...