You're absolutely right. The logomaker library is better suited for position probability matrices (PPMs) or position weight matrices (PWMs) with positive values. Let me revise the script to properly handle your PWM with negative values by converting it to a more appropriate format:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import logomaker
def create_sequence_logo(pwm_file, output_file='sequence_logo.png'):
"""
Create a sequence logo from a PWM text file with negative values.
Parameters:
- pwm_file: Path to the text file containing the PWM
- output_file: Path to save the sequence logo image
"""
# Read the PWM from the text file
pwm_df = pd.read_csv(pwm_file, sep='\t', index_col='pos')
# Convert PWM to PPM (Position Probability Matrix)
# First, exponentiate the PWM values (assuming log-odds scores)
exp_pwm = np.exp(pwm_df)
# Normalize to get probabilities that sum to 1 for each position
ppm_df = exp_pwm.divide(exp_pwm.sum(axis=1), axis=0)
# Calculate information content for each position
# Assuming uniform background (0.25 for each nucleotide)
background = {'A': 0.25, 'C': 0.25, 'G': 0.25, 'T': 0.25}
entropy = -np.sum(ppm_df.multiply(np.log2(ppm_df.replace(0, 1))), axis=1) # Replace 0 with 1 to avoid log(0)
max_entropy = -np.sum([p * np.log2(p) for p in background.values() if p > 0])
info_content = max_entropy - entropy
# Scale the PPM by information content to get the height matrix
height_matrix = ppm_df.multiply(info_content, axis=0)
# Create the logo
logo = logomaker.Logo(height_matrix,
font_name='Arial',
color_scheme='classic',
vpad=0.05,
width=0.8)
# Style the logo
logo.style_spines(visible=False)
logo.ax.set_xticks(range(len(ppm_df)))
logo.ax.set_xticklabels(ppm_df.index)
logo.ax.set_xlabel('Position')
logo.ax.set_ylabel('Information content (bits)')
logo.ax.set_title('Sequence Logo')
logo.ax.set_ylim(0, 2) # Set y-axis limit to 2 bits (for DNA)
# Save and show the logo
plt.savefig(output_file, dpi=300, bbox_inches='tight')
plt.show()
# Example usage
if __name__ == "__main__":
create_sequence_logo('pwm.txt') # Replace with your file path
Would you like me to explain how this script handles the negative values in your PWM?