Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
64f58ae
Simplifying MultiPlot Interface #83
Nishantrde Mar 26, 2025
9c4a5f1
Simplifying MultiPlot Interface #83-2
Nishantrde Mar 26, 2025
4e9485c
Simplifying MultiPlot Interface #83-3
Nishantrde Mar 26, 2025
0f478a5
Simplifying MultiPlot Interface #83-3(enhancing plot function in Spec…
Nishantrde Mar 27, 2025
f873b43
Simplifying MultiPlot Interface #83-resolving_conflick-1
Nishantrde Mar 28, 2025
a33fee3
Simplifying MultiPlot Interface #83-resolving_conflick-2
Nishantrde Mar 28, 2025
8ffab60
Simplifying MultiPlot Interface #83-resolving_conflick-3
Nishantrde Mar 28, 2025
ae057f9
Simplifying MultiPlot Interface #83-resolving_conflick-4
Nishantrde Mar 29, 2025
3cc3963
Simplifying MultiPlot Interface #83-resolving_conflick-5
Nishantrde Mar 30, 2025
29dbd1e
Simplifying MultiPlot Interface #83-resolving_conflick-6
Nishantrde Mar 30, 2025
93af845
Simplifying MultiPlot Interface #83-resolving_conflick-7
Nishantrde Mar 30, 2025
c2aa90c
Simplifying MultiPlot Interface #83-resolving_conflick-8
Nishantrde Mar 30, 2025
f35157d
Simplifying MultiPlot Interface #83-resolving_conflick-9
Nishantrde Mar 30, 2025
82dfd03
Simplifying MultiPlot Interface #83-resolving_conflick-10
Nishantrde Mar 30, 2025
76d56a3
Simplifying MultiPlot Interface #83-resolving_conflick-11
Nishantrde Mar 30, 2025
ad2104a
Simplifying MultiPlot Interface #83-resolving_conflick-12
Nishantrde Mar 30, 2025
f37941f
Simplifying MultiPlot Interface #83-resolving_conflick-13
Nishantrde Mar 30, 2025
6785a32
Simplifying MultiPlot Interface #83-resolving_conflick-14
Nishantrde Apr 1, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,26 +1,40 @@
"""
Investigate Spctrum Binning ms_matplotlib
Investigate Spectrum Binning ms_matplotlib
=======================================

Here we use a dummy spectrum example to investigate spectrum binning.
Here we use a dummy spectrum example to investigate spectrum binning.
"""

import pandas as pd
import matplotlib.pyplot as plt
import requests
from io import StringIO
import sys
import os

# # Add parent directories to the path (adjust as necessary)
# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))

# Set the plotting backend to ms_matplotlib
pd.options.plotting.backend = "ms_matplotlib"

# download the file for example plotting
url = (
"https://github.com/OpenMS/pyopenms_viz/releases/download/v0.1.5/TestSpectrumDf.tsv"
)
# Download the file for example plotting
url = "https://github.com/OpenMS/pyopenms_viz/releases/download/v0.1.5/TestSpectrumDf.tsv"
response = requests.get(url)
response.raise_for_status() # Check for any HTTP errors
df = pd.read_csv(StringIO(response.text), sep="\t")

# Let's assess the peak binning and create a 4 by 2 subplot to visualize the different methods of binning
# Add a 'Run' column and duplicate entries for each run group.
# For example, here we create three run groups (1, 2, and 3).
runs = [1, 2, 3]
df_list = []
for run in runs:
df_run = df.copy()
df_run["Run"] = run
df_list.append(df_run)
df = pd.concat(df_list, ignore_index=True)

# Update the parameters for binning and visualization.
params_list = [
{"title": "Spectrum (Raw)", "bin_peaks": False},
{
Expand Down Expand Up @@ -72,18 +86,26 @@
},
]

# Create a 3-row subplot
# Create a 4x2 subplot grid to visualize different binning methods.
fig, axs = plt.subplots(4, 2, figsize=(14, 14))

i = j = 0
for params in params_list:
p = df.plot(
kind="spectrum", x="mz", y="intensity", canvas=axs[i][j], grid=False, **params
# Here we pass the "Run" column to group the spectrum by run.
df.plot(
kind="spectrum",
x="mz",
y="intensity",
canvas=axs[i][j],
grid=False,
show_plot=False,
by="Run",
**params
)
j += 1
if j >= 2: # If we've filled two columns, move to the next row
if j >= 2: # Move to next row when two columns are filled.
j = 0
i += 1

fig.tight_layout()
fig.show()
plt.show()
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
"""
Plot Spyogenes subplots ms_matplotlib
=======================================
====================================================

Here we show how we can plot multiple chromatograms across runs together
"""

import pandas as pd
import requests
import zipfile
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))


# Set the plotting backend
pd.options.plotting.backend = "ms_matplotlib"

###### Load Data #######
Expand All @@ -21,76 +25,51 @@

# Download the zip file
try:
# Save the zip file to the current directory
print(f"Downloading {zip_filename}...")
response = requests.get(url)
response.raise_for_status() # Check for any HTTP errors

# Save the zip file to the current directory
Comment on lines -27 to -28
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add this back

with open(zip_filename, "wb") as out:
out.write(response.content)
print(f"Downloaded {zip_filename} successfully.")
except requests.RequestException as e:
print(f"Error downloading zip file: {e}")
except IOError as e:
print(f"Error writing zip file: {e}")

# Unzipping the file
# Unzip the file
try:
with zipfile.ZipFile(zip_filename, "r") as zip_ref:
# Extract all files to the current directory
zip_ref.extractall()
print("Unzipped files successfully.")
except zipfile.BadZipFile as e:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this changed from BadZipFile

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I encountered an error while downloading the ZIP file and wanted to understand the reason, but I forgot to revert the changes.

print(f"Error unzipping file: {e}")

annotation_bounds = pd.read_csv(
"spyogenes/AADGQTVSGGSILYR3_manual_annotations.tsv", sep="\t"
) # contain annotations across all runs
chrom_df = pd.read_csv(
"spyogenes/chroms_AADGQTVSGGSILYR3.tsv", sep="\t"
) # contains chromatogram for precursor across all runs

##### Set Plotting Variables #####
pd.options.plotting.backend = "ms_matplotlib"
RUN_NAMES = [
"Run #0 Spyogenes 0% human plasma",
"Run #1 Spyogenes 0% human plasma",
"Run #2 Spyogenes 0% human plasma",
"Run #3 Spyogenes 10% human plasma",
"Run #4 Spyogenes 10% human plasma",
"Run #5 Spyogenes 10% human plasma",
]

fig, axs = plt.subplots(len(np.unique(chrom_df["run"])), 1, figsize=(10, 15))

# plt.close ### required for running in jupyter notebook setting

# For each run fill in the axs object with the corresponding chromatogram
plot_list = []
for i, run in enumerate(RUN_NAMES):
run_df = chrom_df[chrom_df["run_name"] == run]
current_bounds = annotation_bounds[annotation_bounds["run"] == run]
# Load the data
annotation_bounds = pd.read_csv("spyogenes/AADGQTVSGGSILYR3_manual_annotations.tsv", sep="\t")
chrom_df = pd.read_csv("spyogenes/chroms_AADGQTVSGGSILYR3.tsv", sep="\t")

run_df.plot(
kind="chromatogram",
x="rt",
y="int",
grid=False,
by="ion_annotation",
title=run_df.iloc[0]["run_name"],
title_font_size=16,
xaxis_label_font_size=14,
yaxis_label_font_size=14,
xaxis_tick_font_size=12,
yaxis_tick_font_size=12,
canvas=axs[i],
relative_intensity=True,
annotation_data=current_bounds,
xlabel="Retention Time (sec)",
ylabel="Relative\nIntensity",
annotation_legend_config=dict(show=False),
legend_config={"show": False},
)
##### Plotting Using Tile By #####
# Instead of pre-creating subplots and looping over RUN_NAMES,
# we call the plot method once and provide a facet_column parameter.
fig = chrom_df.plot(
kind="chromatogram",
x="rt",
y="int",
facet_column="run_name", # Automatically groups data by run_name and creates subplots
facet_col_wrap=1, # Layout: 1 column (one subplot per row)
grid=False,
by="ion_annotation",
title_font_size=16,
xaxis_label_font_size=14,
yaxis_label_font_size=14,
xaxis_tick_font_size=12,
yaxis_tick_font_size=12,
relative_intensity=True,
annotation_data=annotation_bounds,
xlabel="Retention Time (sec)",
ylabel="Relative\nIntensity",
annotation_legend_config={"show": False},
legend_config={"show": False},
)

fig.tight_layout()
fig
1 change: 1 addition & 0 deletions pyopenms_viz/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ def _get_call_args(backend_name: str, data: DataFrame, args, kwargs):
("feature_config", None),
("_config", None),
("backend", backend_name),
# ("tile_by", None),
]
else:
raise ValueError(
Expand Down
3 changes: 3 additions & 0 deletions pyopenms_viz/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ def default_legend_factory():
legend_config: LegendConfig | dict = field(default_factory=default_legend_factory)
opacity: float = 1.0

facet_column: str | None = None # Name of the column to tile the plot by.
facet_col_wrap: int = 1 # How many columns in the subplot grid.

def __post_init__(self):
# if legend_config is a dictionary, update it to LegendConfig object
if isinstance(self.legend_config, dict):
Expand Down
Loading