Skip to content

analysisPlot

Class to plot results of sanpy.bAnalysis spike detection.

Source code in sanpy/analysisPlot.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
class bAnalysisPlot:
    """
    Class to plot results of [sanpy.bAnalysis][sanpy.bAnalysis] spike detection.

    """

    def __init__(self, ba=None):
        """
        Args:
            ba: [sanpy.bAnalysis][sanpy.bAnalysis] object
        """
        self._ba = ba

    @property
    def ba(self):
        """Get underlying bAnalysis object."""
        return self._ba

    def getDefaultPlotStyle(self):
        """Get dictionary with default plot style."""
        d = {
            "linewidth": 1,
            "color": "k",
            "width": 9,
            "height": 3,
        }
        return d.copy()

    def _makeFig(self, plotStyle=None):
        if plotStyle is None:
            plotStyle = self.getDefaultPlotStyle()

        grid = plt.GridSpec(1, 1, wspace=0.2, hspace=0.4)

        width = plotStyle["width"]
        height = plotStyle["height"]
        fig = plt.figure(figsize=(width, height))
        ax = fig.add_subplot(grid[0, 0:])  # Vm, entire sweep

        ax.spines["right"].set_visible(False)
        ax.spines["top"].set_visible(False)

        return fig, ax

    def plotRaw(self, plotStyle=None, ax=None):
        """
        Plot raw recording

        Args:
            plotStye (float):
            ax (xxx):
        """

        if plotStyle is None:
            plotStyle = self.getDefaultPlotStyle()

        if ax is None:
            _fig, _ax = self._makeFig()
            _fig.suptitle(f"{self._ba.fileLoader.filepath}")
        else:
            _ax = ax

        color = plotStyle["color"]
        linewidth = plotStyle["linewidth"]
        sweepX = self.ba.fileLoader.sweepX
        sweepY = self.ba.fileLoader.sweepY

        _ax.plot(
            sweepX, sweepY, "-", c=color, linewidth=linewidth
        )  # fmt = '[marker][line][color]'

        xUnits = self.ba.fileLoader.get_xUnits()
        yUnits = self.ba.fileLoader.get_yUnits()
        _ax.set_xlabel(xUnits)
        _ax.set_ylabel(yUnits)

        return _ax

    def plotDerivAndRaw(self):
        """
        Plot both Vm and the derivative of Vm (dV/dt).

        Args:
            fig (matplotlib.pyplot.figure): An existing figure to plot to.
                see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html

        Return:
            fig and axs
        """

        #
        # make a 2-panel figure
        grid = plt.GridSpec(2, 1, wspace=0.2, hspace=0.4)
        fig = plt.figure(figsize=(10, 8))
        ax1 = fig.add_subplot(grid[0, 0])
        ax2 = fig.add_subplot(grid[1, 0], sharex=ax1)
        ax1.spines["right"].set_visible(False)
        ax1.spines["top"].set_visible(False)
        ax2.spines["right"].set_visible(False)
        ax2.spines["top"].set_visible(False)

        self.plotRaw(ax=ax1)

        sweepX = self.ba.fileLoader.sweepX
        filteredDeriv = self.ba.fileLoader.filteredDeriv
        ax2.plot(sweepX, filteredDeriv)

        ax2.set_ylabel("dV/dt")
        # ax2.set_xlabel('Seconds')

        return fig, [ax1, ax2]

    def plotSpikes(
        self,
        plotThreshold=False,
        plotPeak=False,
        plotStyle=None,
        hue: Optional[str] = "condition",
        markerSize: Optional[int] = 4,
        ax=None,
    ):
        """Plot Vm with spike analysis overlaid as symbols

        Args:
            plotThreshold
            plotPeak
            plotStyle (dict): xxx
            markerSize
            ax (xxx): If specified will plot into a MatPlotLib axes

        Returns
            fig
            ax
        """

        legend = False

        if plotStyle is None:
            plotStyle = self.getDefaultPlotStyle()

        if ax is None:
            fig, ax = self._makeFig()
            fig.suptitle(self.ba.getFileName())
        # plot vm
        self.plotRaw(ax=ax)

        # plot spike times
        if plotThreshold:
            thresholdSec = self.ba.getStat("thresholdSec")  # x
            thresholdVal = self.ba.getStat("thresholdVal")  # y

            ax.plot(thresholdSec, thresholdVal, "pr", markersize=markerSize)
            df = self.ba.spikeDict.asDataFrame()  # regenerates, can be expensive
            # logger.info(f'df hue unique is: {df[hue].unique()}')
            # sns.scatterplot(x='thresholdSec', y='thresholdVal', hue=hue, data=df, ax=ax, legend=legend)

        # plot the peak
        if plotPeak:
            peakPnt = self.ba.getStat("peakPnt")
            # don't use this for Ca++ concentration
            # peakVal = self.ba.getStat('peakVal')
            peakVal = self.ba.fileLoader.sweepY[peakPnt]
            peakSec = [self.ba.fileLoader.pnt2Sec_(x) for x in peakPnt]
            ax.plot(peakSec, peakVal, "oc", markersize=markerSize)

        xUnits = self.ba.fileLoader.get_xUnits()
        yUnits = self.ba.fileLoader.get_yUnits()
        ax.set_xlabel(xUnits)
        ax.set_ylabel(yUnits)

        return ax

    def plotStat(self, xStat: str, yStat: str, hue: Optional[str] = None, ax=None):
        # ax : Optional["matplotlib.axes._subplots.AxesSubplot"] = None):

        legend = False

        if ax is None:
            fig, ax = self._makeFig()
            fig.suptitle(self.ba.getFileName())
        print(type(ax))

        df = self.ba.spikeDict.asDataFrame()  # regenerates, can be expensive
        sns.scatterplot(x=xStat, y=yStat, hue=hue, data=df, ax=ax, legend=legend)

    def plotTimeSeries(ba, stat, halfWidthIdx=0, ax=None):
        """Plot a given spike parameter."""
        if stat == "peak":
            yStatName = "peakVal"
            yStatLabel = "Spike Peak (mV)"
        if stat == "preMin":
            yStatName = "preMinVal"
            yStatLabel = "Pre Min (mV)"
        if stat == "halfWidth":
            yStatName = "widthPnts"
            yStatLabel = "Spike Half Width (ms)"

        #
        # pull
        statX = []
        statVal = []
        for i, spike in enumerate(ba.spikeDict):
            if i == 0 or i == len(ba.spikeTimes) - 1:
                continue
            else:
                statX.append(spike["peakSec"])
                if stat == "halfWidth":
                    statVal.append(spike["widths"][halfWidthIdx]["widthMs"])
                else:
                    statVal.append(spike[yStatName])

        #
        # plot
        if ax is None:
            grid = plt.GridSpec(1, 1, wspace=0.2, hspace=0.4)

            fig = plt.figure(figsize=(10, 8))
            ax = fig.add_subplot(grid[0, 0:])  # Vm, entire sweep

        ax.plot(statX, statVal, "o-k")

        ax.set_ylabel(yStatLabel)
        ax.set_xlabel("Time (sec)")

        return statVal

    def plotISI(ba, ax=None):
        """Plot the inter-spike-interval (sec) between each spike threshold"""
        #
        # pull
        spikeTimes_sec = [x / ba.dataPointsPerMs / 1000 for x in ba.spikeTimes]
        isi = np.diff(spikeTimes_sec)
        isi_x = spikeTimes_sec[0:-1]

        #
        # plot
        if ax is None:
            grid = plt.GridSpec(1, 1, wspace=0.2, hspace=0.4)

            fig = plt.figure(figsize=(10, 8))
            ax = fig.add_subplot(grid[0, 0:])  # Vm, entire sweep

        ax.plot(isi_x, isi, "o-k")

        ax.set_ylabel("Inter-Spike-Interval (sec)")
        ax.set_xlabel("Time (sec)")

    def plotClips(
        self, plotType="Raw", preClipWidth_ms=None, postClipWidth_ms=None, ax=None
    ):
        """Plot clips of all detected spikes

        Clips are created in self.spikeDetect() and default to clipWidth_ms = 100 ms

        Args:
            plotType (str): From [Raw, RawPlusMean, Mean, SD, Var]
            #plotVariance (bool): If tru, plot variance. Otherwise plot all raw clips (black) with mean (red)

        Returns:
            xPlot
            yPlot
        """

        """
        if ax is None:
            grid = plt.GridSpec(1, 1, wspace=0.2, hspace=0.4)

            fig = plt.figure(figsize=(10, 8))
            ax = fig.add_subplot(grid[0, 0:]) #Vm, entire sweep
        """

        if self.ba.numSpikes == 0:
            return None, None

        if ax is None:
            fig, ax = self._makeFig()
            fig.suptitle(self.ba.getFileName())

        startSec, stopSec = None, None
        selectedSpikeList = []
        # preClipWidth_ms = 200
        # postClipWidth_ms = 1000

        # Leave this none, if we pass none, ba.getSpikeClipsWill take care of this
        """
        if preClipWidth_ms is None:
            preClipWidth_ms = self.ba.detectionClass['preSpikeClipWidth_ms']
        if postClipWidth_ms is None:
            postClipWidth_ms = self.ba.detectionClass['postSpikeClipWidth_ms']
        """
        sweepNumber = 0
        theseClips, theseClips_x, meanClip = self.ba.getSpikeClips(
            startSec,
            stopSec,
            spikeSelection=selectedSpikeList,
            preSpikeClipWidth_ms=preClipWidth_ms,
            postSpikeClipWidth_ms=postClipWidth_ms,
            sweepNumber=sweepNumber,
        )
        numClips = len(theseClips)

        # convert clips to 2d ndarray ???
        xTmp = np.array(theseClips_x)
        # xTmp /= self.ba.dataPointsPerMs * 1000  # pnt to seconds
        xTmp /= 1000  # ms to seconds
        yTmp = np.array(theseClips)  # mV

        # TODO: plot each clip as different color
        # this will show variation in sequential clips (for Ca++ imaging they are decreasing)
        # print(xTmp.shape)  # ( e.g. (9,306)
        # sys.exit(1)

        # plot variance
        if plotType == "Mean":
            xPlot = np.nanmean(xTmp, axis=0)  # xTmp is in ms
            yPlot = np.nanmean(yTmp, axis=0)
            ax.plot(xPlot, yPlot, "-k", linewidth=1)
            ax.set_ylabel("Mean")
            ax.set_xlabel("Time (sec)")
        elif plotType == "Var":
            xPlot = np.nanmean(xTmp, axis=0)  # xTmp is in ms
            yPlot = np.nanvar(yTmp, axis=0)
            ax.plot(xPlot, yPlot, "-k", linewidth=1)
            ax.set_ylabel("Variance")
            ax.set_xlabel("Time (sec)")
        elif plotType == "SD":
            xPlot = np.nanmean(xTmp, axis=0)  # xTmp is in ms
            yPlot = np.nanstd(yTmp, axis=0)
            ax.plot(xPlot, yPlot, "-k", linewidth=1)
            ax.set_ylabel("STD")
            ax.set_xlabel("Time (sec)")
        elif plotType in ["Raw", "RawPlusMean"]:
            # plot raw
            # logger.info('PLOTTING RAW')

            cmap = plt.get_cmap("jet")
            colors = [cmap(i) for i in np.linspace(0, 1, numClips)]

            for i in range(numClips):
                color = colors[i]
                xPlot = xTmp[i, :]
                yPlot = yTmp[i, :]
                # I want different colors here
                # ax.plot(xPlot, yPlot, '-k', linewidth=0.5)
                # WHY IS THIS NOT WORKING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                # logger.info(f'!!!!!!!!!!!!!!!!!!!!!! plotting color g {plotType} {color}')
                # ax.plot(xPlot, yPlot, '-g', linewidth=0.5, color='g')
                ax.plot(xPlot, yPlot, "-", label=f"{i}", color=color, linewidth=0.5)

            yLabel = self.ba._sweepLabelY
            ax.set_ylabel(yLabel)
            ax.set_xlabel("Time (sec)")

            # plot mean
            if plotType == "RawPlusMean":
                xMeanClip = np.nanmean(xTmp, axis=0)  # xTmp is in ms
                yMeanClip = np.nanmean(yTmp, axis=0)
                ax.plot(xMeanClip, yMeanClip, "-r", linewidth=1)

            # show legend for each raw race 0,1,2,3,...
            ax.legend(loc="best")

        else:
            logger.error(f"Did not understand plot type: {plotType}")

        #
        return xPlot, yPlot

    def plotPhasePlot(self, oneSpikeNumber=None, ax=None):
        if ax is None:
            grid = plt.GridSpec(1, 1, wspace=0.2, hspace=0.4)

            fig = plt.figure(figsize=(10, 8))
            ax = fig.add_subplot(grid[0, 0:])  # Vm, entire sweep

        filteredClip = scipy.signal.medfilt(self.spikeClips[oneSpikeNumber], 3)
        dvdt = np.diff(filteredClip)
        # add an initial point so it is the same length as raw data in abf.sweepY
        dvdt = np.concatenate(([0], dvdt))
        (line,) = ax.plot(filteredClip, dvdt, "y")

        ax.set_ylabel("filtered dV/dt")
        ax.set_xlabel("filtered Vm (mV)")

        return line

Attributes¤

ba property ¤

Get underlying bAnalysis object.

Functions¤

__init__(ba=None) ¤

Args: ba: sanpy.bAnalysis object

Source code in sanpy/analysisPlot.py
124
125
126
127
128
129
def __init__(self, ba=None):
    """
    Args:
        ba: [sanpy.bAnalysis][sanpy.bAnalysis] object
    """
    self._ba = ba

getDefaultPlotStyle() ¤

Get dictionary with default plot style.

Source code in sanpy/analysisPlot.py
136
137
138
139
140
141
142
143
144
def getDefaultPlotStyle(self):
    """Get dictionary with default plot style."""
    d = {
        "linewidth": 1,
        "color": "k",
        "width": 9,
        "height": 3,
    }
    return d.copy()

plotClips(plotType='Raw', preClipWidth_ms=None, postClipWidth_ms=None, ax=None) ¤

Plot clips of all detected spikes

Clips are created in self.spikeDetect() and default to clipWidth_ms = 100 ms

Args: plotType (str): From [Raw, RawPlusMean, Mean, SD, Var] #plotVariance (bool): If tru, plot variance. Otherwise plot all raw clips (black) with mean (red)

Returns: xPlot yPlot

Source code in sanpy/analysisPlot.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
def plotClips(
    self, plotType="Raw", preClipWidth_ms=None, postClipWidth_ms=None, ax=None
):
    """Plot clips of all detected spikes

    Clips are created in self.spikeDetect() and default to clipWidth_ms = 100 ms

    Args:
        plotType (str): From [Raw, RawPlusMean, Mean, SD, Var]
        #plotVariance (bool): If tru, plot variance. Otherwise plot all raw clips (black) with mean (red)

    Returns:
        xPlot
        yPlot
    """

    """
    if ax is None:
        grid = plt.GridSpec(1, 1, wspace=0.2, hspace=0.4)

        fig = plt.figure(figsize=(10, 8))
        ax = fig.add_subplot(grid[0, 0:]) #Vm, entire sweep
    """

    if self.ba.numSpikes == 0:
        return None, None

    if ax is None:
        fig, ax = self._makeFig()
        fig.suptitle(self.ba.getFileName())

    startSec, stopSec = None, None
    selectedSpikeList = []
    # preClipWidth_ms = 200
    # postClipWidth_ms = 1000

    # Leave this none, if we pass none, ba.getSpikeClipsWill take care of this
    """
    if preClipWidth_ms is None:
        preClipWidth_ms = self.ba.detectionClass['preSpikeClipWidth_ms']
    if postClipWidth_ms is None:
        postClipWidth_ms = self.ba.detectionClass['postSpikeClipWidth_ms']
    """
    sweepNumber = 0
    theseClips, theseClips_x, meanClip = self.ba.getSpikeClips(
        startSec,
        stopSec,
        spikeSelection=selectedSpikeList,
        preSpikeClipWidth_ms=preClipWidth_ms,
        postSpikeClipWidth_ms=postClipWidth_ms,
        sweepNumber=sweepNumber,
    )
    numClips = len(theseClips)

    # convert clips to 2d ndarray ???
    xTmp = np.array(theseClips_x)
    # xTmp /= self.ba.dataPointsPerMs * 1000  # pnt to seconds
    xTmp /= 1000  # ms to seconds
    yTmp = np.array(theseClips)  # mV

    # TODO: plot each clip as different color
    # this will show variation in sequential clips (for Ca++ imaging they are decreasing)
    # print(xTmp.shape)  # ( e.g. (9,306)
    # sys.exit(1)

    # plot variance
    if plotType == "Mean":
        xPlot = np.nanmean(xTmp, axis=0)  # xTmp is in ms
        yPlot = np.nanmean(yTmp, axis=0)
        ax.plot(xPlot, yPlot, "-k", linewidth=1)
        ax.set_ylabel("Mean")
        ax.set_xlabel("Time (sec)")
    elif plotType == "Var":
        xPlot = np.nanmean(xTmp, axis=0)  # xTmp is in ms
        yPlot = np.nanvar(yTmp, axis=0)
        ax.plot(xPlot, yPlot, "-k", linewidth=1)
        ax.set_ylabel("Variance")
        ax.set_xlabel("Time (sec)")
    elif plotType == "SD":
        xPlot = np.nanmean(xTmp, axis=0)  # xTmp is in ms
        yPlot = np.nanstd(yTmp, axis=0)
        ax.plot(xPlot, yPlot, "-k", linewidth=1)
        ax.set_ylabel("STD")
        ax.set_xlabel("Time (sec)")
    elif plotType in ["Raw", "RawPlusMean"]:
        # plot raw
        # logger.info('PLOTTING RAW')

        cmap = plt.get_cmap("jet")
        colors = [cmap(i) for i in np.linspace(0, 1, numClips)]

        for i in range(numClips):
            color = colors[i]
            xPlot = xTmp[i, :]
            yPlot = yTmp[i, :]
            # I want different colors here
            # ax.plot(xPlot, yPlot, '-k', linewidth=0.5)
            # WHY IS THIS NOT WORKING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            # logger.info(f'!!!!!!!!!!!!!!!!!!!!!! plotting color g {plotType} {color}')
            # ax.plot(xPlot, yPlot, '-g', linewidth=0.5, color='g')
            ax.plot(xPlot, yPlot, "-", label=f"{i}", color=color, linewidth=0.5)

        yLabel = self.ba._sweepLabelY
        ax.set_ylabel(yLabel)
        ax.set_xlabel("Time (sec)")

        # plot mean
        if plotType == "RawPlusMean":
            xMeanClip = np.nanmean(xTmp, axis=0)  # xTmp is in ms
            yMeanClip = np.nanmean(yTmp, axis=0)
            ax.plot(xMeanClip, yMeanClip, "-r", linewidth=1)

        # show legend for each raw race 0,1,2,3,...
        ax.legend(loc="best")

    else:
        logger.error(f"Did not understand plot type: {plotType}")

    #
    return xPlot, yPlot

plotDerivAndRaw() ¤

Plot both Vm and the derivative of Vm (dV/dt).

Args: fig (matplotlib.pyplot.figure): An existing figure to plot to. see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html

Return: fig and axs

Source code in sanpy/analysisPlot.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def plotDerivAndRaw(self):
    """
    Plot both Vm and the derivative of Vm (dV/dt).

    Args:
        fig (matplotlib.pyplot.figure): An existing figure to plot to.
            see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html

    Return:
        fig and axs
    """

    #
    # make a 2-panel figure
    grid = plt.GridSpec(2, 1, wspace=0.2, hspace=0.4)
    fig = plt.figure(figsize=(10, 8))
    ax1 = fig.add_subplot(grid[0, 0])
    ax2 = fig.add_subplot(grid[1, 0], sharex=ax1)
    ax1.spines["right"].set_visible(False)
    ax1.spines["top"].set_visible(False)
    ax2.spines["right"].set_visible(False)
    ax2.spines["top"].set_visible(False)

    self.plotRaw(ax=ax1)

    sweepX = self.ba.fileLoader.sweepX
    filteredDeriv = self.ba.fileLoader.filteredDeriv
    ax2.plot(sweepX, filteredDeriv)

    ax2.set_ylabel("dV/dt")
    # ax2.set_xlabel('Seconds')

    return fig, [ax1, ax2]

plotISI(ba, ax=None) ¤

Plot the inter-spike-interval (sec) between each spike threshold

Source code in sanpy/analysisPlot.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def plotISI(ba, ax=None):
    """Plot the inter-spike-interval (sec) between each spike threshold"""
    #
    # pull
    spikeTimes_sec = [x / ba.dataPointsPerMs / 1000 for x in ba.spikeTimes]
    isi = np.diff(spikeTimes_sec)
    isi_x = spikeTimes_sec[0:-1]

    #
    # plot
    if ax is None:
        grid = plt.GridSpec(1, 1, wspace=0.2, hspace=0.4)

        fig = plt.figure(figsize=(10, 8))
        ax = fig.add_subplot(grid[0, 0:])  # Vm, entire sweep

    ax.plot(isi_x, isi, "o-k")

    ax.set_ylabel("Inter-Spike-Interval (sec)")
    ax.set_xlabel("Time (sec)")

plotRaw(plotStyle=None, ax=None) ¤

Plot raw recording

Args: plotStye (float): ax (xxx):

Source code in sanpy/analysisPlot.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def plotRaw(self, plotStyle=None, ax=None):
    """
    Plot raw recording

    Args:
        plotStye (float):
        ax (xxx):
    """

    if plotStyle is None:
        plotStyle = self.getDefaultPlotStyle()

    if ax is None:
        _fig, _ax = self._makeFig()
        _fig.suptitle(f"{self._ba.fileLoader.filepath}")
    else:
        _ax = ax

    color = plotStyle["color"]
    linewidth = plotStyle["linewidth"]
    sweepX = self.ba.fileLoader.sweepX
    sweepY = self.ba.fileLoader.sweepY

    _ax.plot(
        sweepX, sweepY, "-", c=color, linewidth=linewidth
    )  # fmt = '[marker][line][color]'

    xUnits = self.ba.fileLoader.get_xUnits()
    yUnits = self.ba.fileLoader.get_yUnits()
    _ax.set_xlabel(xUnits)
    _ax.set_ylabel(yUnits)

    return _ax

plotSpikes(plotThreshold=False, plotPeak=False, plotStyle=None, hue='condition', markerSize=4, ax=None) ¤

Plot Vm with spike analysis overlaid as symbols

Args: plotThreshold plotPeak plotStyle (dict): xxx markerSize ax (xxx): If specified will plot into a MatPlotLib axes

Returns fig ax

Source code in sanpy/analysisPlot.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def plotSpikes(
    self,
    plotThreshold=False,
    plotPeak=False,
    plotStyle=None,
    hue: Optional[str] = "condition",
    markerSize: Optional[int] = 4,
    ax=None,
):
    """Plot Vm with spike analysis overlaid as symbols

    Args:
        plotThreshold
        plotPeak
        plotStyle (dict): xxx
        markerSize
        ax (xxx): If specified will plot into a MatPlotLib axes

    Returns
        fig
        ax
    """

    legend = False

    if plotStyle is None:
        plotStyle = self.getDefaultPlotStyle()

    if ax is None:
        fig, ax = self._makeFig()
        fig.suptitle(self.ba.getFileName())
    # plot vm
    self.plotRaw(ax=ax)

    # plot spike times
    if plotThreshold:
        thresholdSec = self.ba.getStat("thresholdSec")  # x
        thresholdVal = self.ba.getStat("thresholdVal")  # y

        ax.plot(thresholdSec, thresholdVal, "pr", markersize=markerSize)
        df = self.ba.spikeDict.asDataFrame()  # regenerates, can be expensive
        # logger.info(f'df hue unique is: {df[hue].unique()}')
        # sns.scatterplot(x='thresholdSec', y='thresholdVal', hue=hue, data=df, ax=ax, legend=legend)

    # plot the peak
    if plotPeak:
        peakPnt = self.ba.getStat("peakPnt")
        # don't use this for Ca++ concentration
        # peakVal = self.ba.getStat('peakVal')
        peakVal = self.ba.fileLoader.sweepY[peakPnt]
        peakSec = [self.ba.fileLoader.pnt2Sec_(x) for x in peakPnt]
        ax.plot(peakSec, peakVal, "oc", markersize=markerSize)

    xUnits = self.ba.fileLoader.get_xUnits()
    yUnits = self.ba.fileLoader.get_yUnits()
    ax.set_xlabel(xUnits)
    ax.set_ylabel(yUnits)

    return ax

plotTimeSeries(ba, stat, halfWidthIdx=0, ax=None) ¤

Plot a given spike parameter.

Source code in sanpy/analysisPlot.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def plotTimeSeries(ba, stat, halfWidthIdx=0, ax=None):
    """Plot a given spike parameter."""
    if stat == "peak":
        yStatName = "peakVal"
        yStatLabel = "Spike Peak (mV)"
    if stat == "preMin":
        yStatName = "preMinVal"
        yStatLabel = "Pre Min (mV)"
    if stat == "halfWidth":
        yStatName = "widthPnts"
        yStatLabel = "Spike Half Width (ms)"

    #
    # pull
    statX = []
    statVal = []
    for i, spike in enumerate(ba.spikeDict):
        if i == 0 or i == len(ba.spikeTimes) - 1:
            continue
        else:
            statX.append(spike["peakSec"])
            if stat == "halfWidth":
                statVal.append(spike["widths"][halfWidthIdx]["widthMs"])
            else:
                statVal.append(spike[yStatName])

    #
    # plot
    if ax is None:
        grid = plt.GridSpec(1, 1, wspace=0.2, hspace=0.4)

        fig = plt.figure(figsize=(10, 8))
        ax = fig.add_subplot(grid[0, 0:])  # Vm, entire sweep

    ax.plot(statX, statVal, "o-k")

    ax.set_ylabel(yStatLabel)
    ax.set_xlabel("Time (sec)")

    return statVal
All material is Copyright 2011-2023 Robert H. Cudmore