/
Pazhiloyyy1337
/
PIAS
Обзор
Документация
Войти
/
Pazhiloyyy1337
/
PIAS
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/visualization/plotter.py
147 строк
5 KB
Pazhiloyyy1337
upload files
24 дек 2025, 00:16
24 дек 2025, 00:16
53b9983
Код
Авторство
О чём код?
""" Модуль для создания графиков """ import matplotlib.pyplot as plt import pandas as pd import os class HeroPlotter: def __init__(self): # Настройки стиля plt.style.use('seaborn-v0_8-darkgrid') # Цвета для атрибутов self.color_map = { 'agi': '#4CAF50', # Зеленый 'str': '#F44336', # Красный 'int': '#2196F3', # Синий } # Создаем папку для графиков self.figures_path = "../../reports/figures" os.makedirs(self.figures_path, exist_ok=True) def save_figure(self, fig, filename): """Сохранить график""" filepath = os.path.join(self.figures_path, filename) fig.savefig(filepath, dpi=150, bbox_inches='tight') print(f" 📊 Сохранен: {filename}") return filepath def create_winrate_pickrate_plot(self, df, highlight_count=10): """Создать график Win Rate vs Pick Rate""" if df.empty or 'win_rate' not in df.columns or 'pick_rate' not in df.columns: print("❌ Нет данных для графика") return None fig, ax = plt.subplots(figsize=(12, 8)) # Размер точек зависит от пикрата sizes = df['pick_rate'] * 15 # Цвета по атрибутам colors = df['primary_attr'].map(self.color_map).fillna('#808080') # Создаем scatter plot scatter = ax.scatter( df['pick_rate'], df['win_rate'], s=sizes, c=colors, alpha=0.7, edgecolors='white', linewidth=0.5 ) # Линия 50% винрейта ax.axhline(y=50, color='gray', linestyle='--', alpha=0.5) # Подписываем топ героев if highlight_count > 0: # Находим героев с высокой комбинацией винрейта и пикрата df['score'] = df['win_rate'] * df['pick_rate'] / 100 top_heroes = df.nlargest(highlight_count, 'score') for _, row in top_heroes.iterrows(): ax.annotate( row['hero_name'], xy=(row['pick_rate'], row['win_rate']), xytext=(5, 5), textcoords='offset points', fontsize=9, alpha=0.8 ) # Настройки графика ax.set_xlabel('Pick Rate (%)', fontsize=12) ax.set_ylabel('Win Rate (%)', fontsize=12) ax.set_title('Dota 2 Heroes: Win Rate vs Pick Rate (Immortal)', fontsize=14) # Сетка ax.grid(True, alpha=0.3) # Легенда from matplotlib.patches import Patch legend_elements = [ Patch(facecolor=color, label=attr.upper(), alpha=0.7) for attr, color in self.color_map.items() ] ax.legend(handles=legend_elements, title='Attribute', loc='upper left') plt.tight_layout() # Сохраняем self.save_figure(fig, 'winrate_vs_pickrate.png') return fig def create_top_heroes_chart(self, df, metric='win_rate', top_n=15): """Создать chart топ героев""" if df.empty or metric not in df.columns: print(f"❌ Нет данных для графика {metric}") return None # Берем топ N героев top_df = df.nlargest(top_n, metric).sort_values(metric, ascending=True) fig, ax = plt.subplots(figsize=(10, max(6, top_n * 0.4))) # Цвета по атрибутам colors = [self.color_map.get(attr, '#808080') for attr in top_df['primary_attr']] # Горизонтальные бары bars = ax.barh(top_df['hero_name'], top_df[metric], color=colors, alpha=0.8) # Добавляем значения for bar in bars: width = bar.get_width() ax.text( width + 0.05, bar.get_y() + bar.get_height()/2, f'{width:.2f}' if metric == 'win_rate' else f'{width:.3f}', ha='left', va='center', fontsize=9 ) # Настройки title_map = { 'win_rate': 'Win Rate (%)', 'pick_rate': 'Pick Rate (%)' } ax.set_xlabel(title_map.get(metric, metric), fontsize=11) ax.set_title(f'Top {top_n} Heroes by {title_map.get(metric, metric)}', fontsize=13) plt.tight_layout() # Сохраняем self.save_figure(fig, f'top_{top_n}_{metric}.png') return fig # Тест if __name__ == "__main__": plotter = HeroPlotter() print("✅ Модуль plotter загружен")