Skip to content

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
DominiqueMakowski committed Jul 22, 2022
1 parent ae345b5 commit 16311e9
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 50 deletions.
36 changes: 25 additions & 11 deletions neurokit2/ecg/ecg_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,20 @@ def ecg_plot(ecg_signals, rpeaks=None, sampling_rate=None, show_type="default"):
Visualize the ECG data with ``"default"`` or visualize artifacts thresholds with
``"artifacts"`` produced by ``ecg_fixpeaks()``, or ``"full"`` to visualize both.
See Also
--------
ecg_process
Returns
-------
Though the function returns nothing, the figure can be retrieved and saved as follows:
.. code-block:: console
# To be run after ecg_plot()
fig = plt.gcf()
fig.savefig("myfig.png")
Examples
--------
.. ipython:: python
Expand All @@ -47,15 +61,8 @@ def ecg_plot(ecg_signals, rpeaks=None, sampling_rate=None, show_type="default"):
@savefig p_ecg_plot.png scale=100%
nk.ecg_plot(signals, sampling_rate=1000, show_type='default')
@suppress
# Save plot
plt.savefig("ecg.png", dpi=300)
plt.close()
See Also
--------
ecg_process
"""
# Sanity-check input.
if not isinstance(ecg_signals, pd.DataFrame):
Expand Down Expand Up @@ -130,7 +137,9 @@ def ecg_plot(ecg_signals, rpeaks=None, sampling_rate=None, show_type="default"):
# Optimize legend
handles, labels = ax0.get_legend_handles_labels()
order = [2, 0, 1, 3]
ax0.legend([handles[idx] for idx in order], [labels[idx] for idx in order], loc="upper right")
ax0.legend(
[handles[idx] for idx in order], [labels[idx] for idx in order], loc="upper right"
)

# Plot heart rate.
ax1.set_title("Heart Rate")
Expand All @@ -154,7 +163,9 @@ def ecg_plot(ecg_signals, rpeaks=None, sampling_rate=None, show_type="default"):
ax2.plot(heartbeats_pivoted)

cmap = iter(
plt.cm.YlOrRd(np.linspace(0, 1, num=int(heartbeats["Label"].nunique()))) # pylint: disable=E1101
plt.cm.YlOrRd(
np.linspace(0, 1, num=int(heartbeats["Label"].nunique()))
) # pylint: disable=E1101
) # Aesthetics of heart beats

lines = []
Expand All @@ -166,10 +177,13 @@ def ecg_plot(ecg_signals, rpeaks=None, sampling_rate=None, show_type="default"):
if show_type in ["artifacts", "full"]:
if sampling_rate is None:
raise ValueError(
"NeuroKit error: ecg_plot(): Sampling rate must be specified for artifacts" " to be plotted."
"NeuroKit error: ecg_plot(): Sampling rate must be specified for artifacts"
" to be plotted."
)

if rpeaks is None:
_, rpeaks = ecg_peaks(ecg_signals["ECG_Clean"], sampling_rate=sampling_rate)

fig = signal_fixpeaks(rpeaks, sampling_rate=sampling_rate, iterative=True, show=True, method="Kubios")
fig = signal_fixpeaks(
rpeaks, sampling_rate=sampling_rate, iterative=True, show=True, method="Kubios"
)
21 changes: 16 additions & 5 deletions neurokit2/emg/emg_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,28 +18,39 @@ def emg_plot(emg_signals, sampling_rate=None):
data should be plotted over time in seconds. Otherwise the data is plotted over samples.
Defaults to ``None``.
See Also
--------
emg_process
Returns
-------
fig
Figure representing a plot of the processed emg signals.
Though the function returns nothing, the figure can be retrieved and saved as follows:
.. code-block:: console
# To be run after emg_plot()
fig = plt.gcf()
fig.savefig("myfig.png")
Examples
--------
.. ipython:: python
import neurokit2 as nk
# Simulate data
emg = nk.emg_simulate(duration=10, sampling_rate=1000, burst_number=3)
# Process signal
emg_signals, _ = nk.emg_process(emg, sampling_rate=1000)
# Plot
@savefig p_emg_plot.png scale=100%
nk.emg_plot(emg_signals)
@suppress
plt.close()
See Also
--------
ecg_process
"""
# Mark onsets, offsets, activity
Expand Down
33 changes: 23 additions & 10 deletions neurokit2/eog/eog_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@ def eog_plot(eog_signals, peaks=None, sampling_rate=None):
the data should be plotted over time in seconds. Otherwise the data is plotted over
samples. Defaults to ``None``. Must be specified to plot individual blinks.
See Also
--------
eog_process
Returns
-------
Though the function returns nothing, the figure can be retrieved and saved as follows:
.. code-block:: console
# To be run after eog_plot()
fig = plt.gcf()
fig.savefig("myfig.png")
Examples
--------
.. ipython:: python
Expand All @@ -39,15 +53,8 @@ def eog_plot(eog_signals, peaks=None, sampling_rate=None):
@savefig p.eog_plot.png scale=100%
nk.eog_plot(eog_signals, peaks, sampling_rate=100)
@suppress
# Save plot
plt.savefig("eog.png", dpi=300)
plt.close()
See Also
--------
eog_process
"""

# Sanity-check input.
Expand Down Expand Up @@ -80,12 +87,16 @@ def eog_plot(eog_signals, peaks=None, sampling_rate=None):
# Plot cleaned and raw EOG
ax0.set_title("Raw and Cleaned Signal")
ax0.plot(x_axis, eog_signals["EOG_Raw"], color="#B0BEC5", label="Raw", zorder=1)
ax0.plot(x_axis, eog_signals["EOG_Clean"], color="#49A4FD", label="Cleaned", zorder=1, linewidth=1.5)
ax0.plot(
x_axis, eog_signals["EOG_Clean"], color="#49A4FD", label="Cleaned", zorder=1, linewidth=1.5
)
ax0.set_ylabel("Amplitude (mV)")

# Plot blinks
blinks = np.where(eog_signals["EOG_Blinks"] == 1)[0]
ax0.scatter(x_axis[blinks], eog_signals["EOG_Clean"][blinks], color="#0146D7", label="Blinks", zorder=2)
ax0.scatter(
x_axis[blinks], eog_signals["EOG_Clean"][blinks], color="#0146D7", label="Blinks", zorder=2
)
ax0.legend(loc="upper right")

# Rate
Expand All @@ -109,7 +120,9 @@ def eog_plot(eog_signals, peaks=None, sampling_rate=None):
epochs_end=0.7,
)
events_array = epochs_to_array(events) # Convert to 2D array
events_array = standardize(events_array) # Rescale so that all the blinks are on the same scale
events_array = standardize(
events_array
) # Rescale so that all the blinks are on the same scale

blinks_df = epochs_to_df(events)
blinks_wide = blinks_df.pivot(index="Time", columns="Label", values="Signal")
Expand Down
4 changes: 3 additions & 1 deletion neurokit2/hrv/hrv_frequency.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ def hrv_frequency(
peaks, sampling_rate = peaks[0], peaks[1]

# Compute R-R intervals (also referred to as NN) in milliseconds (interpolated at 1000 Hz by default)
rri, sampling_rate = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=True, **kwargs)
rri, sampling_rate = _hrv_get_rri(
peaks, sampling_rate=sampling_rate, interpolate=True, **kwargs
)

frequency_band = [ulf, vlf, lf, hf, vhf]

Expand Down
32 changes: 22 additions & 10 deletions neurokit2/ppg/ppg_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ def ppg_plot(ppg_signals, sampling_rate=None):
The sampling frequency of the PPG (in Hz, i.e., samples/second). Needs to be supplied if
the data should be plotted over time in seconds. Otherwise the data is plotted over samples. Defaults to ``None``.
See Also
--------
ppg_process
Returns
-------
Though the function returns nothing, the figure can be retrieved and saved as follows:
.. code-block:: console
# To be run after ppg_plot()
fig = plt.gcf()
fig.savefig("myfig.png")
Examples
--------
.. ipython:: python
Expand All @@ -31,21 +45,15 @@ def ppg_plot(ppg_signals, sampling_rate=None):
@savefig p_ppg_plot1.png scale=100%
nk.ppg_plot(signals)
@suppress
# Save plot
plt.savefig("ppg.png", dpi=300)
plt.close()
See Also
--------
ppg_process
"""

# Sanity-check input.
if not isinstance(ppg_signals, pd.DataFrame):
raise ValueError(
"NeuroKit error: The `ppg_signals` argument must" " be the DataFrame returned by `ppg_process()`."
"NeuroKit error: The `ppg_signals` argument must"
" be the DataFrame returned by `ppg_process()`."
)

# X-axis
Expand All @@ -69,11 +77,15 @@ def ppg_plot(ppg_signals, sampling_rate=None):
# Plot cleaned and raw PPG
ax0.set_title("Raw and Cleaned Signal")
ax0.plot(x_axis, ppg_signals["PPG_Raw"], color="#B0BEC5", label="Raw", zorder=1)
ax0.plot(x_axis, ppg_signals["PPG_Clean"], color="#FB1CF0", label="Cleaned", zorder=1, linewidth=1.5)
ax0.plot(
x_axis, ppg_signals["PPG_Clean"], color="#FB1CF0", label="Cleaned", zorder=1, linewidth=1.5
)

# Plot peaks
peaks = np.where(ppg_signals["PPG_Peaks"] == 1)[0]
ax0.scatter(x_axis[peaks], ppg_signals["PPG_Clean"][peaks], color="#D60574", label="Peaks", zorder=2)
ax0.scatter(
x_axis[peaks], ppg_signals["PPG_Clean"][peaks], color="#D60574", label="Peaks", zorder=2
)
ax0.legend(loc="upper right")

# Rate
Expand Down
29 changes: 20 additions & 9 deletions neurokit2/rsp/rsp_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,20 @@ def rsp_plot(rsp_signals, sampling_rate=None):
sampling_rate : int
The desired sampling rate (in Hz, i.e., samples/second).
See Also
--------
rsp_process
Returns
-------
Though the function returns nothing, the figure can be retrieved and saved as follows:
.. code-block:: console
# To be run after rsp_plot()
fig = plt.gcf()
fig.savefig("myfig.png")
Examples
--------
.. ipython:: python
Expand All @@ -30,15 +44,8 @@ def rsp_plot(rsp_signals, sampling_rate=None):
@savefig p_rsp_plot1.png scale=100%
fig = nk.rsp_plot(rsp_signals)
@suppress
# Save plot
plt.savefig("rsp.png", dpi=300)
plt.close()
See Also
--------
rsp_process
"""
# Mark peaks, troughs and phases.
peaks = np.where(rsp_signals["RSP_Peaks"] == 1)[0]
Expand Down Expand Up @@ -67,7 +74,9 @@ def rsp_plot(rsp_signals, sampling_rate=None):
fig.suptitle("Respiration (RSP)", fontweight="bold")

ax0.plot(x_axis, rsp_signals["RSP_Raw"], color="#B0BEC5", label="Raw", zorder=1)
ax0.plot(x_axis, rsp_signals["RSP_Clean"], color="#2196F3", label="Cleaned", zorder=2, linewidth=1.5)
ax0.plot(
x_axis, rsp_signals["RSP_Clean"], color="#2196F3", label="Cleaned", zorder=2, linewidth=1.5
)

ax0.scatter(
x_axis[peaks],
Expand Down Expand Up @@ -118,7 +127,9 @@ def rsp_plot(rsp_signals, sampling_rate=None):
if "RSP_Amplitude" in list(rsp_signals.columns):
ax2.set_title("Breathing Amplitude")

ax2.plot(x_axis, rsp_signals["RSP_Amplitude"], color="#009688", label="Amplitude", linewidth=1.5)
ax2.plot(
x_axis, rsp_signals["RSP_Amplitude"], color="#009688", label="Amplitude", linewidth=1.5
)
amplitude_mean = np.mean(rsp_signals["RSP_Amplitude"])
ax2.axhline(y=amplitude_mean, label="Mean", linestyle="--", color="#009688")
ax2.legend(loc="upper right")
Expand Down
21 changes: 17 additions & 4 deletions neurokit2/signal/signal_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
from ..stats import standardize as nk_standardize


def signal_plot(signal, sampling_rate=None, subplots=False, standardize=False, labels=None, **kwargs):
def signal_plot(
signal, sampling_rate=None, subplots=False, standardize=False, labels=None, **kwargs
):
"""**Plot signal with events as vertical lines**
Parameters
Expand All @@ -27,6 +29,20 @@ def signal_plot(signal, sampling_rate=None, subplots=False, standardize=False, l
**kwargs : optional
Arguments passed to matplotlib plotting.
See Also
--------
ecg_plot, rsp_plot, ppg_plot, emg_plot, eog_plot
Returns
-------
Though the function returns nothing, the figure can be retrieved and saved as follows:
.. code-block:: console
# To be run after signal_plot()
fig = plt.gcf()
fig.savefig("myfig.png")
Examples
----------
.. ipython:: python
Expand All @@ -53,9 +69,6 @@ def signal_plot(signal, sampling_rate=None, subplots=False, standardize=False, l
nk.signal_plot(data, labels=['signal_1', 'signal_2', 'signal_3'], subplots=True)
nk.signal_plot([signal, data], standardize=True)
@suppress
# Save plot
plt.savefig("signal.png", dpi=300)
plt.close()
"""
Expand Down

0 comments on commit 16311e9

Please sign in to comment.