con todos datos.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import matplotlib.gridspec as gridspec
  4. import numpy as np
  5. import warnings
  6. warnings.filterwarnings('ignore')
  7. # ── Leer datos ──────────────────────────────────────────────────────────────
  8. df = pd.read_csv(
  9. 'resultados1.txt',
  10. sep=r'\s+',
  11. decimal=',',
  12. header=0
  13. )
  14. # Variables de interés
  15. inputs = ['H', 'b', 'tf', 'tw', 'e', 'L']
  16. outputs = ['Flecha_Media', 'Peso']
  17. # Convertir a numérico por si acaso
  18. for col in inputs + outputs:
  19. df[col] = pd.to_numeric(df[col], errors='coerce')
  20. df.dropna(subset=inputs + outputs, inplace=True)
  21. print(f"Filas cargadas: {len(df)}")
  22. print(df[inputs + outputs].describe().to_string())
  23. # ── Paleta de colores ────────────────────────────────────────────────────────
  24. COLORS = {
  25. 'H': '#E63946',
  26. 'b': '#457B9D',
  27. 'tf': '#2A9D8F',
  28. 'tw': '#E9C46A',
  29. 'e': '#F4A261',
  30. 'L': '#A8DADC',
  31. }
  32. BG = '#0F1117'
  33. GRID = '#2A2D3A'
  34. TEXT = '#E8EAF6'
  35. plt.rcParams.update({
  36. 'figure.facecolor': BG,
  37. 'axes.facecolor': BG,
  38. 'axes.edgecolor': GRID,
  39. 'axes.labelcolor': TEXT,
  40. 'xtick.color': TEXT,
  41. 'ytick.color': TEXT,
  42. 'grid.color': GRID,
  43. 'text.color': TEXT,
  44. 'font.family': 'monospace',
  45. })
  46. labels = {
  47. 'H': 'H (altura)',
  48. 'b': 'b (ancho)',
  49. 'tf': 'tf (ala)',
  50. 'tw': 'tw (alma)',
  51. 'e': 'e (excentr.)',
  52. 'L': 'L (longitud)',
  53. }
  54. # ════════════════════════════════════════════════════════════════════════════
  55. # FIGURA 1 – Scatter: cada entrada vs Flecha_Media y Peso
  56. # ════════════════════════════════════════════════════════════════════════════
  57. fig1, axes = plt.subplots(
  58. 2, 6, figsize=(22, 8),
  59. facecolor=BG,
  60. gridspec_kw={'hspace': 0.45, 'wspace': 0.35}
  61. )
  62. fig1.suptitle('Entradas vs Salidas · Scatter', fontsize=15, fontweight='bold',
  63. color=TEXT, y=1.01)
  64. for col_idx, inp in enumerate(inputs):
  65. for row_idx, out in enumerate(outputs):
  66. ax = axes[row_idx, col_idx]
  67. color = COLORS[inp]
  68. # Muestreo para no saturar
  69. sample = df[[inp, out]].dropna().sample(min(2000, len(df)), random_state=42)
  70. ax.scatter(sample[inp], sample[out],
  71. s=6, alpha=0.35, color=color, linewidths=0)
  72. # Línea de tendencia
  73. z = np.polyfit(sample[inp], sample[out], 1)
  74. p = np.poly1d(z)
  75. xs = np.linspace(sample[inp].min(), sample[inp].max(), 200)
  76. ax.plot(xs, p(xs), color='white', lw=1.2, alpha=0.7)
  77. if out == 'Flecha_Media':
  78. ax.axhline(-25, color='white', lw=1.2, linestyle='--', alpha=0.85, label='-25')
  79. ax.legend(fontsize=7, framealpha=0.2, labelcolor=TEXT)
  80. ax.set_xlabel(labels[inp], fontsize=8)
  81. ax.set_ylabel(out, fontsize=8)
  82. ax.grid(True, linestyle='--', alpha=0.3)
  83. ax.tick_params(labelsize=7)
  84. fig1.tight_layout()
  85. fig1.savefig('scatter_entradas_vs_salidas.png',
  86. dpi=150, bbox_inches='tight', facecolor=BG)
  87. print("✓ scatter_entradas_vs_salidas.png guardado")
  88. # ════════════════════════════════════════════════════════════════════════════
  89. # FIGURA 2 – Distribuciones (histogramas) de entradas + salidas
  90. # ════════════════════════════════════════════════════════════════════════════
  91. all_vars = inputs + outputs
  92. n = len(all_vars)
  93. fig2, axes2 = plt.subplots(2, 4, figsize=(18, 8), facecolor=BG,
  94. gridspec_kw={'hspace': 0.5, 'wspace': 0.35})
  95. fig2.suptitle('Distribución de variables', fontsize=15, fontweight='bold',
  96. color=TEXT, y=1.01)
  97. axes2_flat = axes2.flatten()
  98. for i, var in enumerate(all_vars):
  99. ax = axes2_flat[i]
  100. clr = COLORS.get(var, '#90CAF9')
  101. data = df[var].dropna()
  102. ax.hist(data, bins=40, color=clr, alpha=0.85, edgecolor='none')
  103. ax.axvline(data.mean(), color='white', lw=1.4, linestyle='--', label=f'μ={data.mean():.3g}')
  104. ax.set_title(var, fontsize=10, fontweight='bold', color=clr)
  105. ax.set_ylabel('Frecuencia', fontsize=8)
  106. ax.grid(True, linestyle='--', alpha=0.3)
  107. ax.tick_params(labelsize=7)
  108. ax.legend(fontsize=7, framealpha=0.2, labelcolor=TEXT)
  109. # Ocultar último subplot vacío si n < 8
  110. for j in range(n, len(axes2_flat)):
  111. axes2_flat[j].set_visible(False)
  112. fig2.tight_layout()
  113. fig2.savefig('distribuciones.png',
  114. dpi=150, bbox_inches='tight', facecolor=BG)
  115. print("✓ distribuciones.png guardado")
  116. # ════════════════════════════════════════════════════════════════════════════
  117. # FIGURA 3 – Correlación: heatmap
  118. # ════════════════════════════════════════════════════════════════════════════
  119. corr = df[inputs + outputs].corr()
  120. fig3, ax3 = plt.subplots(figsize=(9, 7), facecolor=BG)
  121. fig3.suptitle('Mapa de correlación', fontsize=14, fontweight='bold', color=TEXT)
  122. cmap = plt.cm.RdYlGn
  123. im = ax3.imshow(corr.values, cmap=cmap, vmin=-1, vmax=1, aspect='auto')
  124. plt.colorbar(im, ax=ax3, fraction=0.046, pad=0.04).ax.tick_params(colors=TEXT)
  125. ticks = list(range(len(corr.columns)))
  126. ax3.set_xticks(ticks); ax3.set_yticks(ticks)
  127. ax3.set_xticklabels(corr.columns, rotation=45, ha='right', fontsize=9)
  128. ax3.set_yticklabels(corr.columns, fontsize=9)
  129. for i in range(len(corr)):
  130. for j in range(len(corr)):
  131. val = corr.values[i, j]
  132. color_txt = 'black' if abs(val) > 0.5 else TEXT
  133. ax3.text(j, i, f'{val:.2f}', ha='center', va='center',
  134. fontsize=8, color=color_txt, fontweight='bold')
  135. ax3.grid(False)
  136. fig3.tight_layout()
  137. fig3.savefig('correlacion_heatmap.png',
  138. dpi=150, bbox_inches='tight', facecolor=BG)
  139. print("✓ correlacion_heatmap.png guardado")
  140. # ════════════════════════════════════════════════════════════════════════════
  141. # FIGURA 4 – Boxplots de salidas por cuantiles de L
  142. # ════════════════════════════════════════════════════════════════════════════
  143. df['L_cat'] = pd.qcut(df['L'], q=5, labels=['L_Q1','L_Q2','L_Q3','L_Q4','L_Q5'])
  144. fig4, axes4 = plt.subplots(1, 2, figsize=(14, 6), facecolor=BG)
  145. fig4.suptitle('Distribución de salidas por cuantiles de L', fontsize=14,
  146. fontweight='bold', color=TEXT)
  147. palette = ['#E63946','#F4A261','#E9C46A','#2A9D8F','#457B9D']
  148. for ax_idx, out in enumerate(outputs):
  149. ax = axes4[ax_idx]
  150. groups = [df.loc[df['L_cat'] == cat, out].dropna().values
  151. for cat in df['L_cat'].cat.categories]
  152. bp = ax.boxplot(groups, patch_artist=True, notch=False,
  153. medianprops=dict(color='white', lw=2),
  154. whiskerprops=dict(color=TEXT),
  155. capprops=dict(color=TEXT),
  156. flierprops=dict(marker='o', color=TEXT, alpha=0.2, markersize=2))
  157. for patch, clr in zip(bp['boxes'], palette):
  158. patch.set_facecolor(clr)
  159. patch.set_alpha(0.75)
  160. ax.set_xticklabels(df['L_cat'].cat.categories, rotation=20, fontsize=8)
  161. ax.set_title(out, fontsize=11, fontweight='bold', color=TEXT)
  162. ax.set_ylabel(out, fontsize=9)
  163. ax.grid(True, axis='y', linestyle='--', alpha=0.3)
  164. fig4.tight_layout()
  165. fig4.savefig('boxplot_salidas_por_L.png',
  166. dpi=150, bbox_inches='tight', facecolor=BG)
  167. print("✓ boxplot_salidas_por_L.png guardado")
  168. print("\n✅ Todos los gráficos generados correctamente.")