Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Amazon Novaamazon.nova-pro-v1:0’s answer.
  1. User

    import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle

    Load the coverage data for all 8 datasets

    positive_strands = [] negative_strands = [] for i in range(1, 9): positive_strands.append(np.load(f'positive_strand_coverage{i}.npy')) negative_strands.append(np.load(f'negative_strand_coverage{i}.npy') * -1) # Invert negative strand values

    Load filtered data

    positive_filtered = np.load('positive_filtered.npy') negative_filtered = np.load('negative_filtered.npy') * -1 # Invert for plotting

    Load slide detector data

    prefix_file="sliding_scores-full-offset-cutoff7.02" slide_detector_pos = np.load(prefix_file+'-pos.npy') slide_detector_neg = np.load(prefix_file+'-neg.npy') * -1 # Invert negative strand values

    Start-end coordinates

    cus_start, cus_end = 3791355 - 5000, 3792637 + 5000# 1300856-150,1306768+150

    ---------- Prep x-axis and subset ----------

    x_start, x_end = cus_start, cus_end x = np.arange(x_start, x_end)

    Subset the data for all datasets

    pos_subsets = [pos[x_start:x_end] for pos in positive_strands] neg_subsets = [neg[x_start:x_end] for neg in negative_strands]

    Subset filtered data

    pos_filtered_subset = positive_filtered[x_start:x_end] neg_filtered_subset = negative_filtered[x_start:x_end]

    Subset slide detector data

    slide_detector_pos_subset = slide_detector_pos[x_start:x_end] slide_detector_neg_subset = slide_detector_neg[x_start:x_end]

    Calculate global maximum for rectangle height

    global_max_coverage = max( max([subset.max() for subset in pos_subsets]), max([abs(subset.min()) for subset in neg_subsets]), pos_filtered_subset.max(), abs(neg_filtered_subset.min()) ) * 1.05

    ---------- Create the plot ----------

    fig, ax1 = plt.subplots(figsize=(12, 6))

    Define dataset groups with colors and labels

    datasets = [ {'index': 0, 'group': 'IVT (1)', 'color': '#0000ff'}, # Dark blue {'index': 1, 'group': 'IVT (2)', 'color': '#7755ff'}, # Light blue {'index': 2, 'group': 'IVT 10x DNA (3)', 'color': '#66aaee'}, # Green-blue {'index': 3, 'group': 'No polymerase (4)', 'color': '#d62728'}, # Dark red {'index': 4, 'group': 'No polymerase (5)', 'color': '#ff7f0e'}, # Medium red {'index': 5, 'group': 'No polymerase 10x DNA (6)', 'color': '#ff0088'}, # Light red {'index': 6, 'group': 'DNA (7)', 'color': '#17fe1f'}, # Dark green {'index': 7, 'group': 'DNA (8)', 'color': '#9efa15'} # Light green ]

    Plot all datasets

    for dataset in datasets: i = dataset['index'] ax1.plot(x, pos_subsets[i], color=dataset['color'], linewidth=1, label=dataset['group']) ax1.plot(x, neg_subsets[i], color=dataset['color'], linewidth=1)

    regions = [ {'start': 3791355, 'end': 3792551, 'color': 'lightgreen', 'label': 'kbl'}, {'start': 3792553, 'end': 3792637, 'color': 'lightblue', 'label': 'Promoter kblp'}, #{'start': 3913850, 'end': 3913876, 'color': 'khaki', 'label': 'TIR'}, #{'start': 3913803, 'end': 3913858, 'color': 'plum', 'label': 'BCD'}, {'start': 3792553, 'end': 3792577, 'color': 'red', 'label': 'Transcription start'}, #{'start': 1301182, 'end': 1302813, 'color': 'lightgreen', 'label': 'oppA'}, #{'start': 1302899, 'end': 1303819, 'color': 'lightblue', 'label': 'oppB'}, #{'start': 1301182, 'end': 1306768, 'color': "khaki", 'label': 'oppA-oppF'}, #{'start': 1303834, 'end': 1304742, 'color': 'orange', 'label': 'oppC'}, #{'start': 1300856, 'end': 1300915, 'color': 'blue', 'label': 'oppAp2'}, #{'start': 1301025, 'end': 1301084, 'color': 'plum', 'label': 'oppAp'}, ]

    for r in regions: # Positive strand rectangle ax1.add_patch( Rectangle( (r['start'], 0), r['end'] - r['start'], global_max_coverage, facecolor=r['color'], alpha=0.75, label=r['label'] ) ) # Negative strand rectangle ax1.add_patch( Rectangle( (r['start'], -global_max_coverage), r['end'] - r['start'], global_max_coverage, facecolor=r['color'], alpha=0.75 ) )

    Plot filtered data with grey fill

    ax1.plot(x, pos_filtered_subset, color='grey', linewidth=1, label='Filtered') ax1.plot(x, neg_filtered_subset, color='grey', linewidth=1) ax1.fill_between(x, pos_filtered_subset, neg_filtered_subset, color='grey', alpha=0.7)

    Set up the primary y-axis

    ax1.set_ylim(bottom=-global_max_coverage, top=global_max_coverage) ax1.axhline(0, color='black', linewidth=0.5) # Add zero line ax1.set_ylabel('Coverage (positive and negative strands)')

    Create secondary y-axis for slide detector data

    ax2 = ax1.twinx()

    Calculate max for slide detector data for scaling

    slide_detector_max = max( slide_detector_pos_subset.max(), abs(slide_detector_neg_subset.min()) ) * 1.05

    Plot slide detector data on secondary axis

    Lines for the peaks and labels

    ax2.plot(x, slide_detector_pos_subset, color='purple', linewidth=1, label='Matrix s70 Detector (+)') ax2.plot(x, slide_detector_neg_subset, color='magenta', linewidth=1, label='Matrix s70 Detector (-)')

    Fill between the lines and the x-axis (y=0)

    ax2.fill_between(x, slide_detector_pos_subset, 0, color='purple', alpha=0.3) ax2.fill_between(x, slide_detector_neg_subset, 0, color='magenta', alpha=0.3)

    ax2.set_ylim(bottom=-slide_detector_max, top=slide_detector_max) ax2.set_ylabel('-10 box PWM score', color='purple') ax2.tick_params(axis='y', labelcolor='purple') ax2.axhline(0, color='purple', linestyle='--', linewidth=0.5, alpha=0.5) # Optional: add a zero line for the secondary axis

    ---------- Adjust plot cosmetics ----------

    ax1.ticklabel_format(style='plain', axis='x', useOffset=False) ax1.set_xticks(np.arange(x_start, x_end+1, 500)) ax1.set_xticklabels(np.arange(x_start, x_end+1, 500), rotation=45) ax1.set_xlabel('Position') plt.title('Strand-specific coverage across genetic elements')

    Combine legends from both axes

    handles1, labels1 = ax1.get_legend_handles_labels() handles2, labels2 = ax2.get_legend_handles_labels() all_handles = handles1 + handles2 all_labels = labels1 + labels2

    Deduplicate legend entries

    Ensure that labels from plot() are used for the legend, not fill_between() by placing plot() calls first with labels.

    unique_entries = {} for handle, label in zip(all_handles, all_labels): if label not in unique_entries: unique_entries[label] = handle

    ax1.legend( unique_entries.values(), unique_entries.keys(), loc='center left', bbox_to_anchor=(1.1, 0.5), borderaxespad=0, frameon=True ).set_zorder(1000) # Ensure legend is on top

    plt.tight_layout(rect=[0, 0, 0.85, 1]) # Adjust rect to make space for the legend if it's outside plt.show()

    I have a file named "sega007.fasta" with genome sequence in fasta format. Show the bases on the x axis, I want to see letters

  2. Assistant

    Below is a minimal, drop-in addition that

    1. reads the FASTA file,
    2. extracts the reference sequence for the window you are already plotting (x_start : x_end),
    3. puts the individual bases on a second x–axis.

    Because showing thousands of letters would be unreadable, the snippet automatically refuses to draw the sequence if the window is larger than 200 nt (you can change that limit).

    # ─────────── Add right after you define x_start / x_end ────────────
    #
    # 1. Read the genome sequence
    #    (pip install biopython  if you don’t have it yet)
    from Bio import SeqIO
    
    fasta_path = "sega007.fasta"
    seq_record  = next(SeqIO.parse(fasta_path, "fasta"))
    genome_seq  = str(seq_record.seq).upper()
    
    # 2. Slice the part that corresponds to the plot
    seq_slice = genome_seq[x_start : x_end]          # 0-based coordinates!
    window_len = len(seq_slice)
    
    # 3. Decide whether we can sensibly draw every single base
    MAX_BASES_ON_AXIS = 200        # ← raise this if you dare 😅
    show_letters = window_len <= MAX_BASES_ON_AXIS
    
    # ─────────── Keep the rest of your plotting code exactly as it is ───────────
    # ...
    # plt.title('Strand-specific coverage across genetic elements')
    # handles1, labels1 = ax1.get_legend_handles_labels()
    # ...
    # ax1.legend(...)
    # ---------------------------------------------------------------------------
    
    
    # ─────────── Add the sequence letters on a second x-axis ───────────
    if show_letters:
        # A twin x-axis that shares the same data limits
        ax_seq = ax1.twiny()
    
        # Match limits of the main axis
        ax_seq.set_xlim(ax1.get_xlim())
    
        # Put one tick per base
        ax_seq.set_xticks(np.arange(x_start, x_end))
        ax_seq.set_xticklabels(list(seq_slice),
                               fontfamily='monospace',
                               fontsize=7,
                               rotation=90)
    
        # Cosmetic spacing
        ax_seq.tick_params(axis='x', which='major', pad=5)
        ax_seq.set_xlabel('Reference base')
    else:
        print(f"Window is {window_len} bp – too wide to label every base. "
              f"Zoom in (<={MAX_BASES_ON_AXIS} nt) if you want letters.")
    

    📌 Things to keep in mind

    • Coordinate system: Python strings are 0-based, while your genomic positions are usually 1-based.
    If your x_start/x_end variables are 1-based, subtract 1 when slicing:

    seq_slice = genome_seq[x_start-1 : x_end]           # if positions are 1-based
    

    • If you want colour-coded letters (A: green, T: red, etc.) you can iterate over the slice and place ax_seq.text() calls instead of using set_xticklabels().

    • The extra axis will need vertical space. If letters overlap with the legend, increase the figure height or move the legend.

    That’s all you need—run the script, zoom into any ≤ 200 bp window, and the bases will show up on the new axis.

  3. User

    Full Code. NOW!

  4. Assistant

    Here’s a single, copy-paste-and-run script that

    • loads all eight coverage tracks, the filtered data and the sliding-window detector,
    • reads the reference FASTA,
    • plots everything exactly as before, plus a second x-axis that shows the actual bases (letters) when you zoom into a window of reasonable length (≤ 200 nt by default).

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    # ------------------------------------------------------------
    # Imports
    # ------------------------------------------------------------
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle
    
    # -> Only needed for the sequence axis
    from Bio import SeqIO          # pip install biopython
    
    # ------------------------------------------------------------
    # I/O paths
    # ------------------------------------------------------------
    fasta_path = "sega007.fasta"
    
    coverage_prefix_pos = "positive_strand_coverage"
    coverage_prefix_neg = "negative_strand_coverage"
    
    filtered_pos_file   = "positive_filtered.npy"
    filtered_neg_file   = "negative_filtered.npy"
    
    slide_prefix = "sliding_scores-full-offset-cutoff7.02"  # <-- your PWM file prefix
    
    # ------------------------------------------------------------
    # Genomic window you want to see
    # ------------------------------------------------------------
    cus_start, cus_end = 3791355 - 5000, 3792637 + 5000   # edit as required
    x_start, x_end     = cus_start, cus_end               # keep shorthand
    
    # ------------------------------------------------------------
    # Load coverage data (8 experiments)
    # ------------------------------------------------------------
    positive_strands = [np.load(f"{coverage_prefix_pos}{i}.npy") for i in range(1, 9)]
    negative_strands = [np.load(f"{coverage_prefix_neg}{i}.npy") * -1 for i in range(1, 9)]
    
    # Sub-select the window
    x = np.arange(x_start, x_end)
    pos_subsets = [pos[x_start:x_end] for pos in positive_strands]
    neg_subsets = [neg[x_start:x_end] for neg in negative_strands]
    
    # ------------------------------------------------------------
    # Filtered coverage & PWM detector
    # ------------------------------------------------------------
    positive_filtered = np.load(filtered_pos_file)
    negative_filtered = np.load(filtered_neg_file) * -1
    
    pos_filtered_subset = positive_filtered[x_start:x_end]
    neg_filtered_subset = negative_filtered[x_start:x_end]
    
    slide_detector_pos = np.load(slide_prefix + "-pos.npy")
    slide_detector_neg = np.load(slide_prefix + "-neg.npy") * -1
    
    slide_detector_pos_subset = slide_detector_pos[x_start:x_end]
    slide_detector_neg_subset = slide_detector_neg[x_start:x_end]
    
    # ------------------------------------------------------------
    # Reference sequence (FASTA) – for the base letters axis
    # ------------------------------------------------------------
    seq_record = next(SeqIO.parse(fasta_path, "fasta"))
    genome_seq = str(seq_record.seq).upper()
    
    # WARNING:
    # If your genomic positions are 1-based, uncomment the next line
    # x_start -= 1; x_end -= 1
    
    seq_slice    = genome_seq[x_start:x_end]
    window_len   = len(seq_slice)
    MAX_BASES_ON_AXIS = 200                # draw letters only if window ≤ this
    
    # ------------------------------------------------------------
    # Plotting
    # ------------------------------------------------------------
    fig, ax1 = plt.subplots(figsize=(12, 6))
    
    # ---------- Plot every dataset ----------
    datasets = [
        {'index': 0, 'group': 'IVT (1)',                 'color': '#0000ff'},
        {'index': 1, 'group': 'IVT (2)',                 'color': '#7755ff'},
        {'index': 2, 'group': 'IVT 10x DNA (3)',         'color': '#66aaee'},
        {'index': 3, 'group': 'No polymerase (4)',       'color': '#d62728'},
        {'index': 4, 'group': 'No polymerase (5)',       'color': '#ff7f0e'},
        {'index': 5, 'group': 'No polymerase 10x DNA (6)','color': '#ff0088'},
        {'index': 6, 'group': 'DNA (7)',                 'color': '#17fe1f'},
        {'index': 7, 'group': 'DNA (8)',                 'color': '#9efa15'}
    ]
    
    for ds in datasets:
        i = ds['index']
        ax1.plot(x, pos_subsets[i], color=ds['color'], linewidth=1, label=ds['group'])
        ax1.plot(x, neg_subsets[i], color=ds['color'], linewidth=1)
    
    # ---------- Regions (rectangles) ----------
    regions = [
        {'start': 3791355, 'end': 3792551, 'color': 'lightgreen', 'label': 'kbl'},
        {'start': 3792553, 'end': 3792637, 'color': 'lightblue',  'label': 'Promoter kblp'},
        {'start': 3792553, 'end': 3792577, 'color': 'red',        'label': 'Transcription start'},
    ]
    
    # Height for the rectangles = a bit more than the largest coverage signal
    global_max_coverage = max(
        max([subset.max()            for subset in pos_subsets]),
        max([abs(subset.min())       for subset in neg_subsets]),
        pos_filtered_subset.max(),
        abs(neg_filtered_subset.min())
    ) * 1.05
    
    for r in regions:
        # positive strand rect
        ax1.add_patch(Rectangle(
            (r['start'], 0),
            r['end'] - r['start'],
            global_max_coverage,
            facecolor=r['color'], alpha=0.75, label=r['label']
        ))
        # negative strand rect
        ax1.add_patch(Rectangle(
            (r['start'], -global_max_coverage),
            r['end'] - r['start'],
            global_max_coverage,
            facecolor=r['color'], alpha=0.75
        ))
    
    # ---------- Filtered coverage ----------
    ax1.plot(x, pos_filtered_subset, color='grey',   linewidth=1, label='Filtered')
    ax1.plot(x, neg_filtered_subset, color='grey',   linewidth=1)
    ax1.fill_between(x, pos_filtered_subset, neg_filtered_subset, color='grey', alpha=0.7)
    
    # Y-limits primary axis
    ax1.set_ylim(-global_max_coverage, global_max_coverage)
    ax1.axhline(0, color='black', linewidth=0.5)
    ax1.set_ylabel('Coverage (± strands)')
    
    # ---------- Secondary y-axis (PWM detector) ----------
    ax2 = ax1.twinx()
    
    slide_detector_max = max(
        slide_detector_pos_subset.max(),
        abs(slide_detector_neg_subset.min())
    ) * 1.05
    
    ax2.plot(x, slide_detector_pos_subset, color='purple',  linewidth=1, label='Matrix s70 (+)')
    ax2.plot(x, slide_detector_neg_subset, color='magenta', linewidth=1, label='Matrix s70 (-)')
    ax2.fill_between(x, slide_detector_pos_subset, 0, color='purple',  alpha=0.3)
    ax2.fill_between(x, slide_detector_neg_subset, 0, color='magenta', alpha=0.3)
    
    ax2.set_ylim(-slide_detector_max, slide_detector_max)
    ax2.set_ylabel('-10 box PWM score', color='purple')
    ax2.tick_params(axis='y', labelcolor='purple')
    ax2.axhline(0, color='purple', linestyle='--', linewidth=0.5, alpha=0.5)
    
    # ---------- Cosmetics ----------
    ax1.ticklabel_format(style='plain', axis='x', useOffset=False)
    ax1.set_xticks(np.arange(x_start, x_end+1, 500))
    ax1.set_xticklabels(np.arange(x_start, x_end+1, 500), rotation=45)
    ax1.set_xlabel('Position')
    plt.title('Strand-specific coverage across genetic elements')
    
    # Combine & de-duplicate legends
    handles1, labels1 = ax1.get_legend_handles_labels()
    handles2, labels2 = ax2.get_legend_handles_labels()
    uniq = {}
    for h, l in zip(handles1 + handles2, labels1 + labels2):
        if l not in uniq:
            uniq[l] = h
    ax1.legend(uniq.values(), uniq.keys(),
               loc='center left', bbox_to_anchor=(1.02, 0.5'),
               frameon=True).set_zorder(1000)
    
    plt.tight_layout(rect=[0, 0, 0.87, 1])
    
    # ------------------------------------------------------------
    # EXTRA x-axis with base letters (only if window ≤ MAX_BASES_ON_AXIS)
    # ------------------------------------------------------------
    if window_len <= MAX_BASES_ON_AXIS:
        ax_seq = ax1.twiny()
        ax_seq.set_xlim(ax1.get_xlim())
        ax_seq.set_xticks(np.arange(x_start, x_end))
        ax_seq.set_xticklabels(list(seq_slice),
                               fontfamily='monospace', fontsize=7, rotation=90)
        ax_seq.tick_params(axis='x', which='major', pad=5)
        ax_seq.set_xlabel('Reference base')
    else:
        print(f"Window length = {window_len} bp → too wide for base display "
              f"(limit = {MAX_BASES_ON_AXIS}).  Zoom in if you want letters.")
    
    plt.show()
    

    What changed compared with your previous version?

    1. Added Biopython import & FASTA reader (SeqIO.parse).
    2. Extracted the slice seq_slice for the current window.
    3. Built a second x-axis (ax_seq) that shows one tick per base, but only if the window is reasonably small (≤ 200 nt by default).
      Adjust MAX_BASES_ON_AXIS as you see fit.
    4. Minor refactor so everything lives in a single, self-contained file.

    Enjoy!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.