You're absolutely right! The logomaker library is primarily designed for Position Probability Matrices (PPM) or Position Weight Matrices (PWM) with positive values, where each position's values sum to 1 (for PPM) or represent information content (for PWM).
For your matrix which contains negative values (likely log-odds scores), we need to properly transform it before visualization. Here's an improved version that handles negative values correctly:
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 log-odds PWM text file.
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 log-odds scores to probabilities
# First exponentiate to remove log (assuming natural log)
prob_df = np.exp(pwm_df)
# Normalize each position to sum to 1
prob_df = prob_df.div(prob_df.sum(axis=1), axis=0)
# Calculate information content (in bits)
# We'll use 2 bits as maximum information content per position
ic_df = prob_df * 2 # Scale to desired height
# Create the logo
logo = logomaker.Logo(ic_df,
font_name='Arial',
color_scheme='chemistry',
vpad=0.05,
width=0.8)
# Style the logo
logo.style_spines(visible=False)
logo.ax.set_xticks(range(len(ic_df)))
logo.ax.set_xticklabels(ic_df.index)
logo.ax.set_xlabel('Position')
logo.ax.set_ylabel('Information content (bits)')
logo.ax.set_title('Sequence Logo')
# 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
Key Improvements:
-
Handling Negative Values: The script now properly handles your log-odds scores by:
- Exponentiating the values to convert from log space to linear space
- Normalizing each position to sum to 1 (creating proper probabilities)
-
Information Content: The logo now displays information content in bits (a more standard metric for sequence logos) rather than raw scores.
-
Proper Scaling: The maximum height is set to 2 bits (which is the maximum information content for DNA sequences).
Alternative Approach (if you want to show raw scores):
If you specifically want to visualize the raw log-odds scores (with negative values), you could use this modified version:
def create_sequence_logo_raw(pwm_file, output_file='sequence_logo_raw.png'):
"""Visualize raw log-odds scores (with negative values)"""
pwm_df = pd.read_csv(pwm_file, sep='\t', index_col='pos')
# Create logo with raw scores
logo = logomaker.Logo(pwm_df,
font_name='Arial',
color_scheme='chemistry',
vpad=0.05,
width=0.8)
# Style adjustments
logo.style_spines(visible=False)
logo.ax.set_xticks(range(len(pwm_df)))
logo.ax.set_xticklabels(pwm_df.index)
logo.ax.set_xlabel('Position')
logo.ax.set_ylabel('Log-odds score')
logo.ax.set_title('Sequence Logo (Log-odds scores)')
plt.savefig(output_file, dpi=300, bbox_inches='tight')
plt.show()
Choose the version that best matches your visualization needs! The first approach is more standard for sequence logos, while the second shows the actual values from your matrix.