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 (Micronucleus Genotoxicity)
bins_mn = 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])
freq_mn = np.array([1.02, 1.78, 2.21, 2.59, 2.38, 3.35, 3.99, 4.33, 4.97, 5.14, 5.86, 5.48, 5.65, 6.07, 7.35, 6.88, 7.69, 8.79, 9.00, 5.39, 0.08])
# 2. PCHIP Interpolation (Preserves empirical shape without false oscillations)
interpolator = PchipInterpolator(bins_mn, freq_mn)
x_fit = np.linspace(0, 1, 500)
y_fit = interpolator(x_fit)
# Empirical weighted average
mean_val = np.average(bins_mn, weights=freq_mn)
# 3. Color Function (Probability of Genetic Damage)
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_mn)
# Apply 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.90) for c in colors_hex]
# 4. Create the chart
plt.figure(figsize=(7, 6))
# Draw bars and the new empirical trend line
plt.bar(bins_mn, freq_mn, width=0.04, color=face_colors, edgecolor=edge_colors, linewidth=1.5, zorder=2)
# 5. Tags and Titles
plt.xlabel('Genotoxicity Probability Score (Micronucleus Assay)', fontsize=12)
plt.ylabel('% Frequency', fontsize=12)
plt.title('In Vivo Genotoxicity Potential (Chromosomal Damage)', fontsize=14)
# 6. Legend
legend_elements = [
Patch(facecolor=mcolors.to_rgba('#008000', 0.8), edgecolor='#008000', label='Low Risk (< 0.4)'),
Patch(facecolor=mcolors.to_rgba('#FFD700', 0.8), edgecolor='#FFD700', label='Moderate Risk (0.4 - 0.7)'),
Patch(facecolor=mcolors.to_rgba('#B22222', 0.8), edgecolor='#B22222', label='High Risk (> 0.7)'),
]
plt.legend(handles=legend_elements, loc='upper left', framealpha=0.95, fontsize=10)
plt.grid(axis='y', linestyle=':', alpha=0.7, zorder=0)
plt.xlim(-0.05, 1.05)
plt.ylim(0, 11)
plt.tight_layout()
plt.show()