swharden / pyABF

pyABF is a Python package for reading electrophysiology data from Axon Binary Format (ABF) files

Home Page:https://swharden.com/pyabf

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

plot sweeps color-coded by sweep number

saglag opened this issue · comments

I'm trying to display the instantaneous current versus voltage in demo file DM1_0002.abf. Whenever I try to plot, I only get points of all the same color. As they're separate sweeps, I would like to have a single line for each sweep.

import pyabf
import matplotlib.pyplot as plt

abf = pyabf.ABF("DM1_0002.abf")
print(abf)

cm = plt.get_cmap("viridis")
colors = [cm(x/abf.sweepCount) for x in abf.sweepList]

pt1 = int(294.64 * abf.dataPointsPerMs)
pt2 = int(895.82 * abf.dataPointsPerMs)

currents=[]
voltage=[]
for sweep in abf.sweepList:
    abf.setSweep(sweep)
    currents.append(abf.sweepY[pt1:pt2])
    voltage.append(abf.sweepC[pt1:pt2])

plt.figure(figsize=(8, 5))
plt.grid(alpha=.5, ls='--')
plt.plot(voltage, currents, '.-', ms=15, color=colors[sweep], alpha=.5)

plt.ylabel(abf.sweepLabelY)
plt.xlabel(f"Voltage (mV)")
plt.title(f"Instaneous IV Relationship of {abf.abfID}")

plt.savefig(f'IV Curve of {abf.abfID}.pdf', format='pdf')
plt.show()

The core issue is that color=colors[sweep] is outside your loop so you get the same color every time. This code fixes this and makes a few other improvements:

abf = pyabf.ABF("DM1_0002.abf")

colormap = plt.get_cmap("viridis")
fractions = [sweepNumber / abf.sweepCount for sweepNumber in abf.sweepList]
sweepColors = [colormap(fraction) for fraction in fractions]

pt1 = int(294.64 * abf.dataPointsPerMs)
pt2 = int(895.82 * abf.dataPointsPerMs)

plt.figure(figsize=(8, 5))
plt.grid(alpha=.5, ls='--')

for sweepNumber in abf.sweepList:
    abf.setSweep(sweepNumber)
    current = abf.sweepY[pt1:pt2]
    voltage = abf.sweepC[pt1:pt2]
    plt.plot(voltage, current, color=sweepColors[sweepNumber],
                label=f"sweep {sweepNumber+1}", alpha=.5)

plt.legend(loc = "lower right")
plt.margins(0, .1)
plt.ylabel(abf.sweepLabelY)
plt.xlabel(f"Voltage (mV)")
plt.title(f"Instaneous IV Relationship of {abf.abfID}")
plt.show()

Figure_1