How can I use yasa.plot_spectrogram(), to plot an all-night multi-taper sound spectrogram and add a hypnogram (of the three sleep stages: WAKE, NREM, REM) at the top, which defaults to five stages?Or any other way? #214
Replies: 2 comments
-
yasa_example_night_young.edf |
Beta Was this translation helpful? Give feedback.
0 replies
-
Duplicate of #212 and now converted to an active Issue in #215. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I code to implement it:

What I want: this one is a PS realization

My code: using the quickstart dataset but with a change in sleep staging.This code uses a different dataset than the graph I showed, but the code logic is the same
Clear all variables from the workspace
%reset -f
import mne
import pandas as pd
import yasa
import numpy as np
import matplotlib.pyplot as plt
Load the EDF file containing EEG data
raw = mne.io.read_raw_edf("/Users/ding/Desktop/yasa_example_night_young.edf", preload=True)
print("Original channel names:", raw.ch_names) # Display the original channel names
Drop unnecessary channels
try:
raw.drop_channels(["ROC-A1", "LOC-A2", "EMG1-EMG2", "EKG-R-EKG-L"])
except ValueError as e:
print(f"Error while dropping channels: {e}")
remaining_channels = raw.ch_names
print("Remaining channel names:", remaining_channels) # Display the remaining channel names
Get the original sampling frequency and resample to 100 Hz
original_sampling_rate = raw.info["sfreq"]
print("Original sampling rate:", original_sampling_rate) # Display the original sampling rate
raw.resample(100)
updated_sampling_rate = raw.info["sfreq"] # Update the sampling rate after resampling
print("Updated sampling rate:", updated_sampling_rate) # Display the updated sampling rate
Apply a band-pass filter (0.3 - 45 Hz)
raw.filter(0.3, 45)
Extract the data and convert it to microvolts (µV)
data = raw.get_data(units="uV") #
data
is a NumPy arrayprint("Data shape:", data.shape) # Display the shape of the data array
Load the sleep stage labels from a CSV file
hypnogram_file_path = "/Users/ding/Desktop/yasa_exa
yasa_example_night_young_hypno.csv
yasa_example_night_young_hypno.csv
mple_night_young_hypno.csv"
Read the CSV file, assuming the first column contains the sleep stage labels
try:
hypnogram_labels = pd.read_csv(hypnogram_file_path, header=None)[0] # Read the first column
except Exception as e:
print(f"Error while reading the sleep stage labels file: {e}")
raise
Create a Hypnogram object, assuming there are 3 sleep stages in the labels
from yasa import Hypnogram
try:
hypnogram = Hypnogram(hypnogram_labels, n_stages=3)
except Exception as e:
print(f"Error while creating the Hypnogram object: {e}")
raise
Visualize the hypnogram
try:
yasa.plot_hypnogram(hypnogram)
plt.show()
except Exception as e:
print(f"Error while visualizing the Hypnogram: {e}")
Map sleep stages to integer values and convert the Hypnogram to a NumPy array
hypnogram.mapping = {'WAKE': 0, 'NREM': 1, 'REM': 4} # Map sleep stages to integers
hypnogram_int_values = hypnogram.as_int()
hypnogram_np_array = hypnogram_int_values.to_numpy()
Upsample the Hypnogram to match the resolution of the EEG data
try:
upsampled_hypnogram = yasa.hypno_upsample_to_data(
hypno=hypnogram_np_array,
sf_hypno=1 / 30, # Hypnogram sampling rate (1 epoch every 30 seconds)
data=raw, # EEG data
sf_data=updated_sampling_rate # EEG data sampling rate
)
print("Length after upsampling:", len(upsampled_hypnogram)) # Display the length of the upsampled Hypnogram
except Exception as e:
print(f"Error during upsampling: {e}")
Plot the spectrogram for the 'C4-A1' channel with the Hypnogram overlay
if "C4-A1" in remaining_channels:
try:
yasa.plot_spectrogram(
data[remaining_channels.index("C4-A1")], # Use data from the 'C4-A1' channel
updated_sampling_rate, # Sampling rate of the EEG data
hypno=upsampled_hypnogram # Use the upsampled Hypnogram
)
plt.show()
except Exception as e:
print(f"Error while plotting the spectrogram: {e}")
else:
print("The channel 'C4-A1' is not present in the data.")
Beta Was this translation helpful? Give feedback.
All reactions