Python script to build Figure 5 (traffic light panels)

"script-number-124": Python script for Figure 5 (traffic light panels).
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import os

# Dictionary with parameters for the Excretion profile

excretion_data = {
    # CLp_c (Probability): Traffic light colors
    "CLp": {"bounds": [0, 0.3, 0.7, 1.0], "colors": ["#63C28D", "#FFDF33", "#C14E4E"]},
    
    # CLr (L/h/kg): Custom palette. Visual bounds set at 0 and 1.5 for proportionality
    "CLr": {"bounds": [0, 0.5, 1.5], "colors": ["#FFE24C", "#7DA7CA"]},
    
    # T50 (-log h): Custom palette. Visual bounds set at -2 and 1
    "T50": {"bounds": [-2, -1, 0, 1], "colors": ["#C96464", "#76C99B", "#7DA7CA"]},
    
    # MRT (-log h): Custom palette. Visual bounds set at -2.4 and 1.2
    "MRT": {"bounds": [-2.4, -1.2, 0, 1.2], "colors": ["#C96464", "#76C99B", "#7DA7CA"]},
}

def create_excretion_bars():
    """
    Generates and saves the proportional bar charts for the Excretion parameters.
    """
    # Dimensions requested: 8 cm x 2 cm (converted to inches for matplotlib)
    fig_width = 8 / 2.54
    fig_height = 1.3 / 2.54

    # Create a new directory specific for Figure 4 (Excretion)
    output_dir = "ADMET_Excretion_Bars"
    os.makedirs(output_dir, exist_ok=True)
    
    # Background color matching the established paper style
    bg_color = '#FFFFFF'

    for param, info in excretion_data.items():
        bounds = info["bounds"]
        colors = info["colors"]
        
        # Format labels: for the extreme visual bounds, we can leave them blank or add > / <
        labels = [str(b) for b in bounds]

        # Initialize figure
        fig, ax = plt.subplots(figsize=(fig_width, fig_height))
        fig.patch.set_facecolor(bg_color)
        ax.set_facecolor(bg_color)

        min_val = bounds[0]
        max_val = bounds[-1]

        # Draw each colored segment proportionally based on value distance
        for i in range(len(colors)):
            start = bounds[i]
            width = bounds[i+1] - bounds[i]
            rect = patches.Rectangle(
                (start, 0), width, 1, 
                facecolor=colors[i], edgecolor='none'
            )
            ax.add_patch(rect)

        # Axes scaling
        ax.set_xlim(min_val, max_val)
        ax.set_ylim(0, 1)

        # X-axis setup (ticks and labels)
        ax.set_xticks(bounds)
        ax.set_xticklabels(labels, rotation=45, ha='right', rotation_mode='anchor', fontsize=9)
        
        # Hide top, left and right spines (borders)
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['left'].set_visible(False)
        
        # Offset the bottom spine slightly downwards so it does not overlap the bar
        ax.spines['bottom'].set_position(('outward', 5))
        ax.spines['bottom'].set_linewidth(1)
        
        # Tick styling
        ax.tick_params(axis='x', direction='out', length=4, width=1, colors='black')
        
        # Completely hide the Y axis
        ax.get_yaxis().set_visible(False)

        # Format parameter label for better readability 
        display_param = param
        if param == "CLr":
            display_param += " (L/h/kg)"
        elif param in ["T50", "MRT"]:
            display_param += " (-log h)"
        elif param == "CLp":
            display_param += " (Prob)"
            
        ax.set_xlabel(display_param, fontsize=11, labelpad=5, weight='bold')

        # Adjust layout manually to prevent UserWarning about margins
        plt.subplots_adjust(bottom=0.45)
        
        # Save the figure
        filename = os.path.join(output_dir, f"{param}_bar.png")
        plt.savefig(filename, dpi=300, bbox_inches='tight', facecolor=fig.get_facecolor())
        plt.close()

if __name__ == "__main__":
    print("Starting generation of Excretion profile bars...")
    create_excretion_bars()
    print("Process completed successfully! Check the 'ADMET_Excretion_Bars' folder.")