Ошибка Seaborn: ссылка на локальную переменную boxprops перед присвоениемPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Ошибка Seaborn: ссылка на локальную переменную boxprops перед присвоением

Сообщение Anonymous »

Я пытаюсь построить график с помощью Seaborn Boxplot, однако получаю следующую ошибку:

Код: Выделить всё

UnboundLocalError: local variable 'boxprops' referenced before assignment
На прошлой неделе эти коды работали нормально. Я пробовал обновить seaborn и pyfolio, но все равно получаю ту же ошибку. Кто-нибудь знает, как это исправить?
Код:

Код: Выделить всё

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

# Generate random data for demonstration
np.random.seed(42)  # Setting a seed for reproducibility

# Example of models
modelslikebrain = ['Model1', 'Model2', 'Model3', 'Model4', 'Model5']

# Generating random data for the DataFrame
data = {'model': [], 'location': [], 'layer': [], 'searchlight': [],
'threshold': [], 'amountpeaks': [], 'stateduration': []}

for model in modelslikebrain:
for location in range(50):
for layer in range(5):
threshold = np.random.uniform(0.5, 1.0)
amountpeaks = np.random.randint(10, 20)
stateduration = np.random.normal(5.0, 1.0)

data['model'].append(model)
data['location'].append(location)
data['layer'].append(layer)
data['searchlight'].append(None)
data['threshold'].append(threshold)
data['amountpeaks'].append(amountpeaks)
data['stateduration'].append(stateduration)

df = pd.DataFrame(data)

# Function to convert lists/arrays to mean values
def convert_to_mean(values):
if isinstance(values, (list, np.ndarray)):
return np.mean(values)
return values

# Create a figure with subplots
fig, axes = plt.subplots(nrows=1, ncols=5, figsize=(25, 6), sharey=True)

for ax, model in zip(axes, modelslikebrain):

filtered_df = df[df['model'] == model].copy()

filtered_df['stateduration'] = filtered_df['stateduration'].apply(convert_to_mean)

grouped = filtered_df.groupby('layer')['stateduration']

sns.boxplot(x='layer', y='stateduration', hue='layer', data=filtered_df, palette='Set2', ax=ax)
ax.set_xlabel('Layer')
ax.set_ylabel('State Duration')
ax.set_title(f'{model}')
ax.get_legend().remove()

fig.suptitle('Distribution of State Duration per Layer in Various Models', fontsize=16)
plt.tight_layout(rect=[0, 0, 1, 0.96])
plt.show()
Ошибка:

Код: Выделить всё

UnboundLocalError
Traceback (most recent call last)
 in ()
14
15     # Create a vertical boxplot using seaborn
---> 16     sns.boxplot(x='layer', y='stateduration', hue='layer', data = filtered_df, palette='Set2', ax=ax)
17     ax.set_xlabel('Layer')
18     ax.set_ylabel('State Duration')

1 frames
/usr/local/lib/python3.10/dist-packages/seaborn/categorical.py in boxplot(data, x, y, hue, order, hue_order, orient, color, palette, saturation, fill, dodge, width, gap, whis, linecolor, linewidth, fliersize, hue_norm, native_scale, log_scale, formatter, legend, ax, **kwargs)
1631     )
1632     linecolor = p._complement_color(linecolor, color, p._hue_map)
-> 1633
1634     p.plot_boxes(
1635         width=width,

/usr/local/lib/python3.10/dist-packages/seaborn/categorical.py in plot_boxes(self, width, dodge, gap, fill, whis, color, linecolor, linewidth, fliersize, plot_kws)
742             ax.add_container(BoxPlotContainer(artists))
743
--> 744         legend_artist = _get_patch_legend_artist(fill)
745         self._configure_legend(ax, legend_artist, boxprops)
746

UnboundLocalError: local variable 'boxprops' referenced before assignment
**Попытки решения:
**
  • Обновление seaborn и pyfolio до последних версий.< /li>
Есть ли у кого-нибудь предложения по решению этой проблемы?

Подробнее здесь: https://stackoverflow.com/questions/786 ... assignment
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»