import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.patches import Patch
import numpy as np
from scipy.interpolate import PchipInterpolator
# 1. Original Data (Hemolytic Toxicity)
bins_ht = np.array([0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0])
freq_ht = np.array([0.51, 9.04, 11.68, 11.42, 10.96, 9.30, 8.45, 7.05, 4.71, 3.91, 3.86, 4.37, 3.82, 3.18, 2.68, 2.85, 1.53, 0.59, 0.04, 0.04, 0.0])
# 2. Dynamic Statistical Calculations
mean_val = np.average(bins_ht, weights=freq_ht)
# PCHIP Interpolation (Empirical Trend)
interpolator = PchipInterpolator(bins_ht, freq_ht)
x_fit = np.linspace(0, 1.0, 500)
y_fit = interpolator(x_fit)
# Prevent the curve from falling below 0 due to mathematical fluctuations
y_fit = np.clip(y_fit, 0, None)
# 3. Color Function (Probability Traffic Light)
def get_colors(bins):
return ['#008000' if b < 0.4 else '#FFD700' if b <= 0.7 else '#B22222' for b in bins]
colors_hex = get_colors(bins_ht)
# Apply separate transparencies (Fill at 60%, Border at 90%)
face_colors = [mcolors.to_rgba(c, alpha=0.60) for c in colors_hex]
edge_colors = [mcolors.to_rgba(c, alpha=0.99) for c in colors_hex]
# 4. Create the chart
plt.figure(figsize=(7, 6))
# Draw bars and empirical trend line
plt.bar(bins_ht, freq_ht, width=0.04, color=face_colors, edgecolor=edge_colors, linewidth=1.5, zorder=2)
# 5. Tags and Titles
plt.xlabel('Hemolytic Toxicity Probability Score', fontsize=12)
plt.ylabel('% Frequency', fontsize=12)
plt.title('Hemolytic Toxicity Potential (Erythrocyte Membrane Lysis)', fontsize=14)
# 6. Structured Legend
legend_elements = [
Patch(facecolor=mcolors.to_rgba('#008000', 0.6), edgecolor='#008000', label='Low Risk (< 0.4)'),
Patch(facecolor=mcolors.to_rgba('#FFD700', 0.6), edgecolor='#FFD700', label='Moderate Risk (0.4 - 0.7)'),
Patch(facecolor=mcolors.to_rgba('#B22222', 0.6), edgecolor='#B22222', label='High Risk (Hemolysis) (> 0.7)'),
# plt.Line2D([0], [0], color='black', lw=2.5, alpha=0.8, label='Empirical Data Trend')
]
plt.legend(handles=legend_elements, loc='upper right', framealpha=0.95, fontsize=10)
plt.grid(axis='y', linestyle=':', alpha=0.7, zorder=0)
plt.xlim(-0.05, 1.05)
plt.ylim(0, 13)
plt.tight_layout()
plt.show()