I have the following problem in a loop, which is practically the same code as another plot I made, but this one keeps giving an error
from matplotlib.cm import get_cmap
from matplotlib.patches import Patch
# Criando um dataframe secundário para analisar as variáveis categoricas Gender, IsActiveMember e Exited
df3 = df1[['Gender', 'IsActiveMember', 'Exited']]
df3['Dummy'] = np.ones(len(df3))
# Agrupando pelas categorias desejadas
grouped = df3.groupby(by=['IsActiveMember', 'Exited', 'Gender']).count().unstack()
# Lista dos clientes em churn ou fora, para usar como categoria depois
kinds = grouped.columns.levels[1]
# Cores para o grafico
colors = [get_cmap('viridis')(v) for v in np.linspace(0,1,len(kinds))]
sns.set(context="talk")
nxplots = len(grouped.index.levels[0])
nyplots = len(grouped.index.levels[1])
fig, axes = plt.subplots(nxplots,
nyplots,
sharey=True,
sharex=True,
figsize=(15,10))
fig.suptitle('Agrupamento Gênero e \nSendo Membro Ativo ou Não')
# plot
for a, b in enumerate(grouped.index.levels[0]):
for i, j in enumerate(grouped.index.levels[1]):
axes[a,i].bar(kinds,grouped.loc[b,j],color=colors)
axes[a,i].xaxis.set_ticks([])
axeslabels = fig.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.grid(False)
axeslabels.set_ylabel('Gênero',rotation='horizontal',y=1,weight="bold")
axeslabels.set_xlabel('Em churn ou não',weight="bold")
# Rotulos dos eixo X e Y
for i, j in enumerate(grouped.index.levels[1]):
axes[nyplots,i].set_xlabel(j)
for i, j in enumerate(grouped.index.levels[0]):
axes[i,0].set_ylabel(j)
# Ajuste manual para abrir espaço para a legenda
fig.subplots_adjust(right=0.78)
fig.legend([Patch(facecolor = i) for i in colors],
kinds,
title="Membro Ativo ou não",
loc="upper right")
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9692/3580268901.py in <module>
40 # Rotulos dos eixo X e Y
41 for i, j in enumerate(grouped.index.levels[1]):
---> 42 axes[nyplots,i].set_xlabel(j)
43 for i, j in enumerate(grouped.index.levels[0]):
44 axes[i,0].set_ylabel(j)
IndexError: index 2 is out of bounds for axis 0 with size 2
I did the same code just now with two other categorical variables and it didn't give an error.
from matplotlib.cm import get_cmap
from matplotlib.patches import Patch
# Criando um dataframe secundário para analisar as variáveis categoricas Geography, NumOfProducts e Exited
df2 = df1[['Geography', 'NumOfProducts', 'Exited']]
df2['Dummy'] = np.ones(len(df2))
# Agrupando pelas categorias desejadas
grouped = df2.groupby(by=['Geography','Exited','NumOfProducts' ]).count().unstack()
# Lista dos clientes em churn ou fora, para usar como categoria depois
kinds = grouped.columns.levels[1]
# Cores para o grafico
colors = [get_cmap('viridis')(v) for v in np.linspace(0,1,len(kinds))]
sns.set(context="talk")
nxplots = len(grouped.index.levels[0])
nyplots = len(grouped.index.levels[1])
fig, axes = plt.subplots(nxplots,
nyplots,
sharey=True,
sharex=True,
figsize=(15,10))
fig.suptitle('Agrupamento de Clientes por Região e \nQuantidade de Produtos')
# plot
for a, b in enumerate(grouped.index.levels[0]):
for i, j in enumerate(grouped.index.levels[1]):
axes[a,i].bar(kinds,grouped.loc[b,j],color=colors)
axes[a,i].xaxis.set_ticks([])
axeslabels = fig.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.grid(False)
axeslabels.set_ylabel('Localidade',rotation='horizontal',y=1,weight="bold")
axeslabels.set_xlabel('Em churn ou não',weight="bold")
# Rotulos dos eixo X e Y
for i, j in enumerate(grouped.index.levels[1]):
axes[nyplots,i].set_xlabel(j)
for i, j in enumerate(grouped.index.levels[0]):
axes[i,0].set_ylabel(j)
# Ajuste manual para abrir espaço para a legenda
fig.subplots_adjust(right=0.78)
fig.legend([Patch(facecolor = i) for i in colors],
kinds,
title="Quantidade de Produtos",
loc="upper right")
What's the problem now in this loop because I can't identify any error in the code to give the loop index a problem