Python matplotlib.pyplot.axvspan() Examples

The following are code examples for showing how to use matplotlib.pyplot.axvspan(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pohmm-keystroke   Author: vmonaco   File: plotting.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_hmm_vs_pohmm_pvalues(hmm_pvalues, pohmm_pvalues, threshold=0.05):
    x = np.linspace(0, 1, 1000)

    plt.figure(figsize=(8, 8))

    plt.plot([], [])
    plt.plot([], [])
    plt.plot([], [])
    plt.plot(x, ECDF(hmm_pvalues.values.squeeze())(x), label='HMM (%.2f)' % ((hmm_pvalues['pvalue'] <= threshold).sum()/len(hmm_pvalues)))
    plt.plot(x, ECDF(pohmm_pvalues.values.squeeze())(x), label='POHMM (%.2f)' % ((pohmm_pvalues['pvalue'] <= threshold).sum()/len(pohmm_pvalues)))
    # plt.plot(x, ECDF(hmm_pvalues.values.squeeze())(x), color=HMM_COLOR, linestyle='-.', label='HMM', linewidth='2.0')
    # plt.plot(x, ECDF(pohmm_pvalues.values.squeeze())(x), color=POHMM_COLOR, label='POHMM')
    plt.plot(x, x, 'k--', linewidth=0.5)
    plt.axvspan(0, threshold, color='k', alpha=0.25)
    plt.minorticks_on()
    plt.xlabel('p-value')
    plt.ylabel('Cumulative distribution')
    # plt.legend(loc='upper left')
    plt.legend(loc='lower right')
    return 
Example 2
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_axvspan_epoch():
    from datetime import datetime
    import matplotlib.testing.jpl_units as units
    units.register()

    # generate some data
    t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
    tf = units.Epoch("ET", dt=datetime(2009, 1, 21))

    dt = units.Duration("ET", units.day.convert("sec"))

    fig = plt.figure()

    plt.axvspan(t0, tf, facecolor="blue", alpha=0.25)

    ax = plt.gca()
    ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt) 
Example 3
Project: itch   Author: bibby   File: __init__.py    MIT License 6 votes vote down vote up
def plot_streams(streams_src, minx, maxx):
    stream_fill_color = 'g'
    with open(streams_src, 'r') as streams:
        for line in streams.readlines():
            start, end = tuple(line.strip().split("\t"))
            start = _dt(start)
            end = _dt(end)

            if minx > end:
                continue
            if maxx < start:
                continue

            plt.axvspan(
                start,
                end,
                facecolor=stream_fill_color,
                alpha=0.5
            ) 
Example 4
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 6 votes vote down vote up
def test_axvspan_epoch():
    from datetime import datetime
    import matplotlib.testing.jpl_units as units
    units.register()

    # generate some data
    t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
    tf = units.Epoch("ET", dt=datetime(2009, 1, 21))

    dt = units.Duration("ET", units.day.convert("sec"))

    fig = plt.figure()

    plt.axvspan(t0, tf, facecolor="blue", alpha=0.25)

    ax = plt.gca()
    ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt) 
Example 5
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_axvspan_epoch():
    from datetime import datetime
    import matplotlib.testing.jpl_units as units
    units.register()

    # generate some data
    t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
    tf = units.Epoch("ET", dt=datetime(2009, 1, 21))

    dt = units.Duration("ET", units.day.convert("sec"))

    fig = plt.figure()

    plt.axvspan(t0, tf, facecolor="blue", alpha=0.25)

    ax = plt.gca()
    ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt) 
Example 6
Project: linear_neuron   Author: uglyboxer   File: test_axes.py    MIT License 6 votes vote down vote up
def test_axvspan_epoch():
    from datetime import datetime
    import matplotlib.testing.jpl_units as units
    units.register()

    # generate some data
    t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
    tf = units.Epoch("ET", dt=datetime(2009, 1, 21))

    dt = units.Duration("ET", units.day.convert("sec"))

    fig = plt.figure()

    plt.axvspan(t0, tf, facecolor="blue", alpha=0.25)

    ax = plt.gca()
    ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt) 
Example 7
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 6 votes vote down vote up
def test_axvspan_epoch():
    from datetime import datetime
    import matplotlib.testing.jpl_units as units
    units.register()

    # generate some data
    t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
    tf = units.Epoch("ET", dt=datetime(2009, 1, 21))

    dt = units.Duration("ET", units.day.convert("sec"))

    fig = plt.figure()

    plt.axvspan(t0, tf, facecolor="blue", alpha=0.25)

    ax = plt.gca()
    ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt) 
Example 8
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_axes.py    MIT License 6 votes vote down vote up
def test_axvspan_epoch():
    from datetime import datetime
    import matplotlib.testing.jpl_units as units
    units.register()

    # generate some data
    t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
    tf = units.Epoch("ET", dt=datetime(2009, 1, 21))

    dt = units.Duration("ET", units.day.convert("sec"))

    fig = plt.figure()

    plt.axvspan(t0, tf, facecolor="blue", alpha=0.25)

    ax = plt.gca()
    ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt) 
Example 9
Project: ImageFusion   Author: pfchai   File: test_axes.py    MIT License 6 votes vote down vote up
def test_axvspan_epoch():
    from datetime import datetime
    import matplotlib.testing.jpl_units as units
    units.register()

    # generate some data
    t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
    tf = units.Epoch("ET", dt=datetime(2009, 1, 21))

    dt = units.Duration("ET", units.day.convert("sec"))

    fig = plt.figure()

    plt.axvspan(t0, tf, facecolor="blue", alpha=0.25)

    ax = plt.gca()
    ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt) 
Example 10
Project: Blackjack-Tracker   Author: martinabeleda   File: test_axes.py    MIT License 6 votes vote down vote up
def test_axvspan_epoch():
    from datetime import datetime
    import matplotlib.testing.jpl_units as units
    units.register()

    # generate some data
    t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
    tf = units.Epoch("ET", dt=datetime(2009, 1, 21))

    dt = units.Duration("ET", units.day.convert("sec"))

    fig = plt.figure()

    plt.axvspan(t0, tf, facecolor="blue", alpha=0.25)

    ax = plt.gca()
    ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt) 
Example 11
Project: FCS_point_correlator   Author: dwaithe   File: correlation_gui.py    GNU General Public License v2.0 6 votes vote down vote up
def on_release(self, event):
        #self.rect.remove()
        self.x1 = event.xdata
        
        if(self.x0 <0): self.x0 =0
        if(self.x1 <0): self.x1 =0
        if(self.x0 >self.x1): self.x1b =self.x0;self.x0=self.x1;self.x0=self.x1b
       

        self.scrollBox.rect.append(plt.axvspan(self.x0, self.x1, facecolor=self.par_obj.colors[self.scrollBox.rect.__len__() % len(self.par_obj.colors)], alpha=0.5,picker=True))
        self.ax.figure.canvas.draw()
        #Saves regions to series of arrays. Opted not to make class for this. Not sure why :-)
        self.scrollBox.x0.append(self.x0)
        self.scrollBox.x1.append(self.x1)
        self.scrollBox.color = self.par_obj.colors[self.scrollBox.rect.__len__()]
        self.scrollBox.TGid.append(self.par_obj.TGnumOfRgn)
        self.scrollBox.facecolor.append(self.par_obj.colors[self.par_obj.TGnumOfRgn])
        self.par_obj.TGnumOfRgn = self.par_obj.TGnumOfRgn + 1
        self.scrollBox.generateList()
        #refreshTable() 
Example 12
Project: ward-metrics   Author: phev8   File: visualisations.py    MIT License 6 votes vote down vote up
def plot_events_with_event_scores(gt_event_scores, detected_event_scores, ground_truth_events, detected_events, show=True):
    fig = plt.figure(figsize=(10, 3))
    for i in range(len(detected_events)):
        d = detected_events[i]
        plt.axvspan(d[0], d[1], 0, 0.5)
        plt.text((d[1] + d[0]) / 2, 0.2, detected_event_scores[i], horizontalalignment='center', verticalalignment='center')

    for i in range(len(ground_truth_events)):
        gt = ground_truth_events[i]
        plt.axvspan(gt[0], gt[1], 0.5, 1)
        plt.text((gt[1] + gt[0]) / 2, 0.8, gt_event_scores[i], horizontalalignment='center', verticalalignment='center')

    plt.tight_layout()

    if show:
        plt.show()
    else:
        plt.draw() 
Example 13
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_axes.py    GNU General Public License v3.0 6 votes vote down vote up
def test_axvspan_epoch():
    from datetime import datetime
    import matplotlib.testing.jpl_units as units
    units.register()

    # generate some data
    t0 = units.Epoch("ET", dt=datetime(2009, 1, 20))
    tf = units.Epoch("ET", dt=datetime(2009, 1, 21))

    dt = units.Duration("ET", units.day.convert("sec"))

    fig = plt.figure()

    plt.axvspan(t0, tf, facecolor="blue", alpha=0.25)

    ax = plt.gca()
    ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt) 
Example 14
Project: SWHLab   Author: swharden   File: protocols.py    MIT License 6 votes vote down vote up
def proto_0101(theABF):
    abf=ABF(theABF)
    abf.log.info("analyzing as an IC tau")
    #plot=ABFplot(abf)

    plt.figure(figsize=(SQUARESIZE/2,SQUARESIZE/2))
    plt.grid()
    plt.ylabel("relative potential (mV)")
    plt.xlabel("time (sec)")
    m1,m2=[.05,.1]
    for sweep in range(abf.sweeps):
        abf.setsweep(sweep)
        plt.plot(abf.sweepX2,abf.sweepY-abf.average(m1,m2),alpha=.2,color='#AAAAFF')
    average=abf.averageSweep()
    average-=np.average(average[int(m1**abf.pointsPerSec):int(m2*abf.pointsPerSec)])
    plt.plot(abf.sweepX2,average,color='b',lw=2,alpha=.5)
    plt.axvspan(m1,m2,color='r',ec=None,alpha=.1)
    plt.axhline(0,color='r',ls="--",alpha=.5,lw=2)
    plt.margins(0,.1)

    # save it
    plt.tight_layout()
    frameAndSave(abf,"IC tau")
    plt.close('all') 
Example 15
Project: SWHLab   Author: swharden   File: 2016-12-15 noise sample.py    MIT License 6 votes vote down vote up
def plot_shaded_data(X,Y,variances,varianceX):
    """plot X and Y data, then shade its background by variance."""
    plt.plot(X,Y,color='k',lw=2)
    nChunks=int(len(Y)/CHUNK_POINTS)
    for i in range(0,100,PERCENT_STEP):
        varLimitLow=np.percentile(variances,i)
        varLimitHigh=np.percentile(variances,i+PERCENT_STEP)
        varianceIsAboveMin=np.where(variances>=varLimitLow)[0]
        varianceIsBelowMax=np.where(variances<=varLimitHigh)[0]
        varianceIsRange=[chunkNumber for chunkNumber in range(nChunks) \
                         if chunkNumber in varianceIsAboveMin \
                         and chunkNumber in varianceIsBelowMax]
        for chunkNumber in varianceIsRange:
            t1=chunkNumber*CHUNK_POINTS/POINTS_PER_SEC
            t2=t1+CHUNK_POINTS/POINTS_PER_SEC
            plt.axvspan(t1,t2,alpha=.3,color=COLORMAP(i/100),lw=0) 
Example 16
Project: pohmm-keystroke   Author: vmonaco   File: plotting.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_pvalues(pvalues, threshold=0.05):
    x = np.linspace(0, 1, 1000)

    plt.figure(figsize=(8, 8))

    ecdf = ECDF(pvalues.values.squeeze())
    plt.plot(x, ecdf(x), color=sns.xkcd_rgb['denim blue'])
    plt.plot(x, x, 'k--')
    plt.axvspan(0, threshold, color='k', alpha=0.25)
    plt.minorticks_on()
    plt.xlabel('p-value')
    plt.ylabel('Cumulative distribution')
    return 
Example 17
Project: genimpro   Author: bastustrump   File: sonicevents.py    MIT License 5 votes vote down vote up
def showAndPlay(events,audio,sequence=[]):
	from utility import float2pcm
	import pyaudio

	p = pyaudio.PyAudio()

	stream = p.open(format=2,channels=1,rate=int(samplerate),output=True)

	samples = audio[events[0]["start"]:events[len(events)-1]["end"]]
	startsample = events[0]["start"]
	plt.plot(samples,"b")

	for i in range (0,len(events)):
		print "mark %i from %i to %i" % (sequence[i],events[i]["start"],events[i]["end"])
		plt.text(events[i]["start"], .05, str(sequence[i]))
		plt.axvspan(events[i]["start"]-startsample, events[i]["end"]-startsample, color='red', alpha=(((i+1)%2)*0.5))

	pcmaudio = float2pcm(samples)
	data = struct.pack(str(len(pcmaudio)) + 'h',*pcmaudio)
	stream.write(data)

	plt.show() #block=False

	stream.stop_stream()
	stream.close()

	p.terminate() 
Example 18
Project: sensor_data_preprocessing   Author: gsprint23   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_acceleration_data(df, sensor_loc, fname=None, section_times=None, labels=None):
    '''
    Plot the acceleration so the user can find the horiz and vert sections.

    Keyword arguments:

    '''
    plt.figure()  
    plt.plot(df.index, df['Wide Range Accelerometer X'], label = 'X-axis') 
    plt.plot(df.index, df['Wide Range Accelerometer Y'], label = 'Y-axis') 
    plt.plot(df.index, df['Wide Range Accelerometer Z'], label = 'Z-axis')   
    
    if section_times is not None and labels is not None:
        plt.axvspan(section_times[0], section_times[1], facecolor='b', alpha=0.5) 
        plt.text(section_times[0], -11, labels[0], style='italic', bbox={'facecolor':'b', 'alpha':0.8, 'pad':10})
            
        plt.axvspan(section_times[2], section_times[3], facecolor='g', alpha=0.5)
        plt.text(section_times[2], -11, labels[1], style='italic', bbox={'facecolor':'g', 'alpha':0.8, 'pad':10}) 
  
   
    plt.xlabel('Timestamp')
    plt.ylabel('Acceleration [m/s^2]')
    plt.title('Sensor location: %s' %(sensor_loc))
    plt.legend()
    if fname is not None:
        plt.savefig(fname)
    plt.show() 
Example 19
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_twinx_knows_limits():
    fig, ax = plt.subplots()

    ax.axvspan(1, 2)
    xtwin = ax.twinx()
    xtwin.plot([0, 0.5], [1, 2])
    # control axis
    fig2, ax2 = plt.subplots()

    ax2.axvspan(1, 2)
    ax2.plot([0, 0.5], [1, 2])

    assert_array_equal(xtwin.viewLim.intervalx, ax2.viewLim.intervalx) 
Example 20
Project: dave   Author: barentsen   File: plotting.py    MIT License 5 votes vote down vote up
def plotTransitRegions(time, period_days, epoch_bkjd, duration_days, **kwargs):
    tmin = np.min(time)
    tmax = np.max(time)

    n1 = int(np.floor( (tmin-epoch_bkjd)/period_days) )
    n2 = int(np.ceil(  (tmax-epoch_bkjd)/period_days) )
    color = kwargs.pop('color','#888888')
    alpha = kwargs.pop('alpha', 1)

    for n in range(n1, n2+1):
        t0 = epoch_bkjd + n*period_days
        lwr = t0 - .5*duration_days
        upr = t0 + .5*duration_days
        plt.axvspan(lwr, upr, color=color, alpha=alpha) 
Example 21
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_twinx_knows_limits():
    fig, ax = plt.subplots()

    ax.axvspan(1, 2)
    xtwin = ax.twinx()
    xtwin.plot([0, 0.5], [1, 2])
    # control axis
    fig2, ax2 = plt.subplots()

    ax2.axvspan(1, 2)
    ax2.plot([0, 0.5], [1, 2])

    assert_array_equal(xtwin.viewLim.intervalx, ax2.viewLim.intervalx) 
Example 22
Project: AC_tools   Author: tsherwen   File: plotting.py    MIT License 5 votes vote down vote up
def plot_gc_bin_bands(facecolor='#B0C4DE'):
    """
    Plot highlighted lines of ("tropospheric") GEOS-Chem/Fast-J photolysis bins
    """
    vars = [GC_var(i) for i in ('FastJ_lower', 'FastJ_upper')]
    alphas = [0.3, 0.1]*len(vars[0])
    [plt.axvspan(vars[0][n], vars[1][n], facecolor=facecolor,
                 alpha=alphas[n]) for n in range(len(vars[0]))] 
Example 23
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_axes.py    MIT License 5 votes vote down vote up
def test_twinx_knows_limits():
    fig, ax = plt.subplots()

    ax.axvspan(1, 2)
    xtwin = ax.twinx()
    xtwin.plot([0, 0.5], [1, 2])
    # control axis
    fig2, ax2 = plt.subplots()

    ax2.axvspan(1, 2)
    ax2.plot([0, 0.5], [1, 2])

    assert_array_equal(xtwin.viewLim.intervalx, ax2.viewLim.intervalx) 
Example 24
Project: qkit   Author: qkitgroup   File: initialize.py    GNU General Public License v2.0 5 votes vote down vote up
def crop_recording_window(self):
        self._sample.mspec.spec_stop()
        self._sample.mspec.set_averages(1e4)
        self._sample.mspec.set_window(0,512)
        self._sample.mspec.set_segments(1)
        msp = self._sample.mspec.acquire()
        
        def pltfunc(start,end,done):
            if done:
                self._sample.acqu_window = [start,end]
                self._sample.mspec.set_window(start,end)
                self._sw.disabled = True
                self._ew.disabled = True
                self._dw.disabled = True
                self._dw.description = "acqu_window set to [{:d}:{:d}]".format(start,end)
            else:
                plt.figure(figsize=(15,5))
                plt.plot(msp)
                plt.axvspan(0,start,color='k',alpha=.2)
                plt.axvspan(end,len(msp),color='k',alpha=.2)
                plt.xlim(0,len(msp))
                plt.show()
        self._sw =  widgets.IntSlider(min=0,max=len(msp),step=1,value=self._sample.acqu_window[0],continuous_update=True)
        self._ew = widgets.IntSlider(min=0,max=len(msp),step=1,value=self._sample.acqu_window[1],continuous_update=True)
        self._dw = widgets.Checkbox(value=False,description="Done!",indent=True)
        self._wgt = widgets.interact(pltfunc,start=self._sw,end=self._ew,done=self._dw)
        self._sample.mspec.set_window(*self._sample.acqu_window) 
Example 25
Project: px4tools   Author: dronecrew   File: analysis.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def background_flight_modes(data):
    """
    Overlays a background color for each flight mode. Can be called to style a graph.
    """
    import matplotlib.pyplot as plt
    modes = np.array(data.STAT_MainState.unique(), np.uint8)
    for m in modes:
        mode_data = data.STAT_MainState[data.STAT_MainState == m]
        mode_name = FLIGHT_MODES[m]
        mode_color = FLIGHT_MODE_COLOR[mode_name]
        t_min = mode_data.index[0]
        t_max = mode_data.index[mode_data.count() - 1]
        plt.axvspan(
            t_min, t_max, alpha=0.1, color=mode_color,
            label=mode_name, zorder=0) 
Example 26
Project: MeteorRadiometer   Author: CroatianMeteorNetwork   File: 2-stage-fit_radiometer.py    MIT License 5 votes vote down vote up
def plotResult(x_data, y_data, func, popt, highlight=False, highlight_min=0, highlight_max=0):
    """ Plots fitted data. """

    # Plot original

    plt.subplot(3, 1, 1)

    if highlight:
        # Highlight the sample area
        plt.axvspan(highlight_min, highlight_max, facecolor='r', alpha=0.5, lw=0)

    plt.plot(x_data, y_data)

    plt.title('Original')
    plt.ylabel('ADU')

    # Plot model
    plt.subplot(3, 1, 2)
    plt.plot(x_data, func(x_data, *popt))

    plt.title('Model')
    plt.ylabel('ADU')


    # Plot filtered
    plt.subplot(3, 1, 3)
    plt.plot(x_data, y_data - func(x_data, *popt))

    plt.title('Filtered')
    plt.xlabel('Time (s)')
    plt.ylabel('ADU')

    plt.show()
    plt.clf() 
Example 27
Project: laserComm   Author: partofthething   File: test_receiver.py    MIT License 5 votes vote down vote up
def test_plot_spans(self):

        p = self.p
        p.receiver.plot(None)
        t = p.receiver.times
        for minI, maxI in p.on_bounds:
            span_min = t[minI]
            span_max = t[maxI]
            plt.axvspan(span_min, span_max, facecolor='g', alpha=0.5)
        plt.show() 
Example 28
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_axes.py    MIT License 5 votes vote down vote up
def test_twinx_knows_limits():
    fig, ax = plt.subplots()

    ax.axvspan(1, 2)
    xtwin = ax.twinx()
    xtwin.plot([0, 0.5], [1, 2])
    # control axis
    fig2, ax2 = plt.subplots()

    ax2.axvspan(1, 2)
    ax2.plot([0, 0.5], [1, 2])

    assert_array_equal(xtwin.viewLim.intervalx, ax2.viewLim.intervalx) 
Example 29
Project: IDAtropy   Author: danigargu   File: IDAtropy.py    GNU General Public License v3.0 5 votes vote down vote up
def segment_changed(self, item):
      row = item.row()
      col = item.column()
      seg_name = item.text()

      if (item.checkState() == QtCore.Qt.Checked):
        start, end = self.segments[seg_name]['chart_offsets']
        aspan = plt.axvspan(start, end, color=self.colors[row % len(self.colors)], alpha=0.6)
        self.spans[seg_name] = aspan      
      else:
        if seg_name in self.spans.keys():
          self.spans[seg_name].remove()
          del self.spans[seg_name]      
      self.canvas.draw() 
Example 30
Project: Blackjack-Tracker   Author: martinabeleda   File: test_axes.py    MIT License 5 votes vote down vote up
def test_twinx_knows_limits():
    fig, ax = plt.subplots()

    ax.axvspan(1, 2)
    xtwin = ax.twinx()
    xtwin.plot([0, 0.5], [1, 2])
    # control axis
    fig2, ax2 = plt.subplots()

    ax2.axvspan(1, 2)
    ax2.plot([0, 0.5], [1, 2])

    assert((xtwin.viewLim.intervalx == ax2.viewLim.intervalx).all()) 
Example 31
Project: FCS_point_correlator   Author: dwaithe   File: correlation_gui.py    GNU General Public License v2.0 5 votes vote down vote up
def freshDraw(self):
            self.scrollBox.rect =[]
            for i in range(0,self.scrollBox.x0.__len__()):
                
                self.scrollBox.rect.append(plt.axvspan(self.scrollBox.x0[i], self.scrollBox.x1[i], facecolor=self.par_obj.colors[i % len(self.par_obj.colors)], alpha=0.5,picker=True))
            self.win_obj.canvas5.draw() 
Example 32
Project: FCS_point_correlator   Author: dwaithe   File: correlation_gui.py    GNU General Public License v2.0 5 votes vote down vote up
def redraw(self):
            
            for i in range(0,self.scrollBox.rect.__len__()):
                self.scrollBox.rect[i].remove()
            self.scrollBox.rect =[]
            for i in range(0,self.scrollBox.x0.__len__()):
                
                self.scrollBox.rect.append(plt.axvspan(self.scrollBox.x0[i], self.scrollBox.x1[i], facecolor=self.par_obj.colors[i % len(self.par_obj.colors)], alpha=0.5,picker=True))
            self.win_obj.canvas5.draw() 
Example 33
Project: IBATS_Common   Author: IBATS   File: plot.py    GNU General Public License v3.0 5 votes vote down vote up
def label_distribution(close_df: pd.DataFrame, min_rr: float, max_rr: float, max_future: int,
                       name=None, **enable_kwargs):
    """
    输出分类标签在行情图中的分布情况
    :param close_df:
    :param min_rr:
    :param max_rr:
    :param max_future:为空则进行2分类,不为空则3分类
    :param enable_kwargs:
    :param name:
    :return:
    """
    logger.debug('%s [%f ~ %f] max_future=%d, name="%s"', close_df.shape, min_rr, max_rr, max_future, name)
    value_arr = close_df.to_numpy()
    if max_future is None:
        target_arr = calc_label2(value_arr, min_rr, max_rr, one_hot=False, dtype='int')
    else:
        target_arr = calc_label3(value_arr, min_rr, max_rr, max_future=max_future, one_hot=False, dtype='int')

    ax = close_df.plot(grid=True)
    plt.suptitle(f'label [{min_rr * 100:.2f}% ~ {max_rr * 100:.2f}%]')
    x_values = list(close_df.index)
    colors = [None, ALTER_BG_COLOR, '#d62728']

    value_count = len(value_arr)
    label_list = list(set(target_arr))
    distribution_rate_df = pd.DataFrame(
        {_: {'pct': sum(target_arr == _) / value_count} for _ in label_list}, columns=label_list)
    for label, range_from, range_to in get_range_num_iter(target_arr):
        color = colors[int(label)]
        if color is None:
            continue
        p = plt.axvspan(x_values[range_from], x_values[range_to], facecolor=color, alpha=0.5)

    file_name = get_file_name(f'label distribution', name=name)
    file_path = plot_or_show(file_name=file_name, **enable_kwargs)
    return distribution_rate_df, file_path 
Example 34
Project: unidip   Author: BenjaminDoran   File: unidip.py    GNU General Public License v3.0 5 votes vote down vote up
def plot(self, sub, ints, plot_style="seaborn"):
        """ Plot complete data, highlight subset currently being searched,
            and add vertical lines for discovered intervals. (only intervals of
            the current recursion level appear.)
        """
        import matplotlib.pyplot as plt
        plt.style.use(plot_style)
        
        if self.is_hist:
            plt.step(list(range(len(self.dat))), self.dat)
            plt.fill_between(list(range(len(self.dat))), self.dat, step="pre", alpha=.4)
            plt.axvspan(sub[0], sub[1]-1, color="orange", alpha=.3)
            for i in ints:
                plt.axvspan(i[0], i[1], color="green", alpha=.1)
            for i in ints:
                plt.axvline(i[0], color="black")
                plt.axvline(i[1], color="black")
        else:
            dat = np.msort(self.dat)
            plt.hist(dat, bins=30)
            plt.axvspan(dat[sub[0]], dat[sub[1]-1], color="orange", alpha=.3)
            for i in ints:
                plt.axvspan(dat[i[0]], dat[i[1]], color="green", alpha=.1)
            for i in ints:
                plt.axvline(dat[i[0]], color="black")
                plt.axvline(dat[i[1]], color="black")
        plt.show() 
Example 35
Project: OASIS   Author: j-friedrich   File: fig2.py    GNU General Public License v3.0 5 votes vote down vote up
def cb(y, P, counter, current):
    solution = np.empty(len(y))
    for v, w, f, l in P:
        solution[f:f + l] = max(v, 0) / w * g**np.arange(l)
    plt.figure(figsize=(3, 3))
    color = y.copy()
    plt.plot(solution, c='k', zorder=-11, lw=1.2)
    plt.scatter(np.arange(len(y)), solution, s=60, cmap=plt.cm.Spectral,
                c=color, clip_on=False, zorder=11)
    plt.scatter([np.arange(len(y))[current]], [solution[current]],
                s=200, lw=2.5, marker='+', color='b', clip_on=False, zorder=11)
    for a in P[::2]:
        plt.axvspan(a[2], a[2] + a[3], alpha=0.1, color='k', zorder=-11)
    for x in np.where(trueSpikes)[0]:
        plt.plot([x, x], [0, 1.65], lw=1.5, c='r', zorder=-12)
    plt.xlim((0, len(y) - .5))
    plt.ylim((0, 1.65))
    simpleaxis(plt.gca())
    plt.xticks([])
    plt.yticks([])
    if save_figs:
        plt.savefig('fig/%d.pdf' % counter)
    plt.show()


# generate data 
Example 36
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_axes.py    GNU General Public License v3.0 5 votes vote down vote up
def test_twinx_knows_limits():
    fig, ax = plt.subplots()

    ax.axvspan(1, 2)
    xtwin = ax.twinx()
    xtwin.plot([0, 0.5], [1, 2])
    # control axis
    fig2, ax2 = plt.subplots()

    ax2.axvspan(1, 2)
    ax2.plot([0, 0.5], [1, 2])

    assert_array_equal(xtwin.viewLim.intervalx, ax2.viewLim.intervalx) 
Example 37
Project: sp500-forecaster   Author: alessandrozamberletti   File: forecaster.py    MIT License 5 votes vote down vote up
def evaluate(self, x, y, ohlcv, ticker):
        preds = self.predict_classes(x)

        plt.cla()

        # no data before timestep and after -futurestep
        chart = ohlcv[self.trasformer.features[-1]].values[self.trasformer.timestep:-self.trasformer.futurestep]
        plt.plot(chart, color='black')

        # gt vs predicted
        for idx, (gt, pred) in enumerate(zip(y, preds)):
            if gt != pred:
                plt.axvspan(idx, idx + 1, fc='gray')
                continue
            plt.axvspan(idx, idx + 1, fc='green', alpha=.5) if pred else plt.axvspan(idx, idx + 1, fc='red', alpha=.5)

        plt.title('Predictions vs Ground Truth - SYMBOL:{}'.format(ticker))
        plt.ylabel('{} price'.format(self.trasformer.features[-1]))
        plt.xlabel('days')

        legend = [mpatches.Patch(label='pos. outlook (gt == pred)', color='green', alpha=.5),
                  mpatches.Patch(label='neg. outlook (gt == pred)', color='red', alpha=.5),
                  mpatches.Patch(label='wrong outlook (gt != pred)', color='gray', alpha=.5)]

        plt.legend(handles=legend)

        return metrics.accuracy_score(y, preds), self.__save_img(ticker) 
Example 38
Project: SWHLab   Author: swharden   File: protocols.py    MIT License 5 votes vote down vote up
def proto_0203(theABF):
    """protocol: vast IV."""
    abf=ABF(theABF)
    abf.log.info("analyzing as a fast IV")
    plot=ABFplot(abf)
    plot.title=""
    m1,m2=.7,1
    plt.figure(figsize=(SQUARESIZE,SQUARESIZE/2))

    plt.subplot(121)
    plot.figure_sweeps()
    plt.axvspan(m1,m2,color='r',ec=None,alpha=.1)

    plt.subplot(122)
    plt.grid(alpha=.5)
    Xs=np.arange(abf.sweeps)*5-110
    Ys=[]
    for sweep in range(abf.sweeps):
        abf.setsweep(sweep)
        Ys.append(abf.average(m1,m2))
    plt.plot(Xs,Ys,'.-',ms=10)
    plt.axvline(-70,color='r',ls='--',lw=2,alpha=.5)
    plt.axhline(0,color='r',ls='--',lw=2,alpha=.5)
    plt.margins(.1,.1)
    plt.xlabel("membrane potential (mV)")

    # save it
    plt.tight_layout()
    frameAndSave(abf,"fast IV")
    plt.close('all') 
Example 39
Project: SWHLab   Author: swharden   File: 01-shadeBLS.py    MIT License 5 votes vote down vote up
def BLS_average(abf):
    T1,T2=epochTimes(abf)
    Tdiff=max([T2-T1,.1])
    X1,X2=T1-Tdiff,T2+Tdiff
    I1,I2=X1*abf.pointsPerSec,X2*abf.pointsPerSec

    plt.figure(figsize=(10,10))
    chunks=np.empty((abf.sweeps,I2-I1))
    Xs=np.array(abf.sweepX2[I1:I2])
    for sweep in abf.setsweeps():
        chunks[sweep]=abf.sweepY[I1:I2]
        plt.subplot(211)
        plt.plot(Xs,chunks[sweep],alpha=.2,color='.5',lw=2)
        plt.subplot(212)
        plt.plot(Xs,chunks[sweep]+100*sweep,alpha=.5,color='b',lw=2)

    plt.subplot(211)
    plt.plot(Xs,np.average(chunks,axis=0),alpha=.5,lw=2)
    plt.title("%s.abf - BLS - average of %d sweeps"%(abf.ID,abf.sweeps))
    plt.ylabel(abf.units2)
    plt.axvspan(T1,T2,alpha=.1,color='y',lw=0)
    plt.axis([X1,X2,None,None])

    plt.subplot(212)
    plt.xlabel("time (sec)")
    plt.ylabel("stacked sweeps")
    plt.axvspan(T1,T2,alpha=.1,color='y',lw=0)
    plt.axis([X1,X2,None,None])

    plt.tight_layout()
    plt.show()
    plt.close('all') 
Example 40
Project: extinction   Author: kbarbary   File: extinction_plot.py    MIT License 5 votes vote down vote up
def extinction_figure(wave, a_lambda, residual_from, residual_lims=(-0.1, 0.4), title_text='$R_V = 3.1$'):

    names = list(a_lambda.keys())  # consistent ordering between panels
    fig = plt.figure(figsize=(8.5, 6.))

    ax = plt.axes()
    for name in names:
        plt.plot(wave, a_lambda[name], label=name)
    plt.axvline(x=2700., ls=':', c='k')
    plt.axvline(x=3030.3030, ls=':', c='k')
    plt.axvline(x=9090.9091, ls=':', c='k')
    plt.axvspan(wave[0], 1150., fc='0.8', ec='none', zorder=-1000)
    plt.axvspan(1150., 1250., fc='0.9', ec='none', zorder=-1000)    
    plt.text(0.65, 0.95, title_text, transform=ax.transAxes, va='top',
             ha='right', size='x-large')
    plt.ylabel('Extinction ($A(\lambda)$ / $A_V$)')
    plt.legend()
    plt.setp(ax.get_xticklabels(), visible=False)

    divider = make_axes_locatable(ax)
    axresid = divider.append_axes("bottom", size=2.0, pad=0.2, sharex=ax)
    for name in names:
        plt.plot(wave, a_lambda[name] - a_lambda[residual_from])
    plt.axvline(x=2700., ls=':', c='k')
    plt.axvline(x=3030.3030, ls=':', c='k')
    plt.axvline(x=9090.9091, ls=':', c='k')
    plt.axvspan(wave[0], 1150., fc='0.8', ec='none', zorder=-1000)
    plt.axvspan(1150., 1250., fc='0.9', ec='none', zorder=-1000)
    plt.xlim(wave[0], wave[-1])
    plt.ylim(ymin=residual_lims[0], ymax=residual_lims[1])
    plt.ylabel('residual from ' + residual_from)
    plt.xlabel(r'Wavelength ($\mathrm{\AA}$)')

    ax.set_xscale('log')
    axresid.set_xscale('log')
    plt.tight_layout()

    return fig 
Example 41
Project: pyABFauto   Author: swharden   File: analysisByProtocol.py    MIT License 5 votes vote down vote up
def shadeDigitalOutput(abf, digitalOutputChannel=4, color='r'):
    """In sweep view, shade the epoch number."""
    log.debug("shading digital outputs")
    digitalWaveforms = pyabf.stimulus.digitalWaveformEpochs(abf)
    epochPoints = pyabf.stimulus.epochPoints(abf)
    outputStateByEpoch = digitalWaveforms[digitalOutputChannel]
    for epochNumber, outputState in enumerate(outputStateByEpoch):
        if outputState == 1:
            t1 = epochPoints[epochNumber]*abf.dataSecPerPoint
            t2 = epochPoints[epochNumber+1]*abf.dataSecPerPoint
            plt.axvspan(t1, t2, color=color, alpha=.3, lw=0) 
Example 42
Project: pyABFauto   Author: swharden   File: analysisByProtocol.py    MIT License 5 votes vote down vote up
def generic_iv(abf, timeSec1, timeSec2, sweepStepMv, firstSweepMv, filter=True):
    """Create a graph plotting the I/V between two points."""

    log.debug("generic plot: IV curve")

    # enable lowpass filter
    if filter:
        pyabf.filter.gaussian(abf, 2)

    # measure currents for each step
    currentAvg = pyabf.stats.rangeAverage(abf, timeSec1, timeSec2)
    currentErr = pyabf.stats.rangeStdev(abf, timeSec1, timeSec2)
    voltage = np.arange(abf.sweepCount)*sweepStepMv+firstSweepMv

    plotFigNew(abf, figsize=FIGSIZE_WIDE)  # double wide
    ax1 = plt.gcf().add_subplot(1, 2, 1)
    ax2 = plt.gcf().add_subplot(1, 2, 2)

    # create the overlay figure
    pyabf.plot.sweeps(abf, axis=ax1, linewidth=2, alpha=.8)
    ax1.axvspan(timeSec1, timeSec2, color='r', alpha=.1)
    ax1.set_title(f"{abf.abfID} I/V Source Sweeps")
    dY = (np.nanmax(currentAvg) - np.nanmin(currentAvg))*.2
    ax1.axis([None, None, np.nanmin(currentAvg)-dY, np.nanmax(currentAvg)+dY])

    # create the IV curve
    ax2.axhline(0, ls='--', alpha=.5, color='k')
    ax2.axvline(-70, ls='--', alpha=.5, color='k')
    ax2.plot(voltage, currentAvg, '.-', lw=2, ms=20)
    ax2.set_ylabel("Current (pA)")
    ax2.set_xlabel("Voltage (mV)")
    ax2.set_title(f"{abf.abfID} I/V Relationship")

    plotFigSave(abf, tag="IV", labelAxes=False) 
Example 43
Project: EBS-search   Author: OrganicMaterialsDatabase   File: preprocessing.py    MIT License 4 votes vote down vote up
def plot_band_structure(folder, band_index, width, k_highlight, pattern):
    """
    - Plots two bands (which one is indicated by band_index)
    - Highlights a window of width `width` at k `k_highlight`
    """
    kpoints = vasp.Kpoints('data/' + folder + '/KPOINTS.gz')
    doscar = vasp.Doscar('data/' + folder + '/DOSCAR.gz')
    fermi_energy = doscar.fermi_energy
    eigenval = vasp.Eigenval('data/' + folder + '/EIGENVAL.gz', fermi_level=fermi_energy)

    bands = eigenval.spin_up
    lower_fermi_band_index = np.argmax(np.nanmax(bands,axis=1) > 0) - 1

    segment_sizes = kpoints.segment_sizes
    segmented_lower_band = np.split(bands[lower_fermi_band_index+band_index], np.cumsum(segment_sizes))[:-1]
    segmented_upper_band = np.split(bands[lower_fermi_band_index+band_index+1], np.cumsum(segment_sizes))[:-1]
    segmented_kpoints = np.split(eigenval.k_points, np.cumsum(segment_sizes))[:-1]

    last_k = 0
    for k, band_l, band_u in zip(segmented_kpoints, segmented_lower_band, segmented_upper_band):
        k_1D = np.array(path_1D(k)) + last_k
        plt.plot(k_1D, band_l, 'k')
        plt.plot(k_1D, band_u, 'k')
        last_k = np.max(k_1D)

    plt.axvspan(k_highlight, k_highlight+width, color='red', alpha=0.5)

    # Collect axis ticks (high symmetry points) from KPOINTS.gz
    last_k = 0
    label_k = []
    label_names = []
    for left_k, right_k in vasp.chunks(kpoints.k_points, 2):
        if len(label_names) == 0:
            label_k.append(last_k)
            label_names.append(left_k[0])
        elif label_names[-1] != left_k[0]:
            label_names[-1] += (';' + left_k[0])
        last_k += np.linalg.norm(right_k[1] - left_k[1])
        label_k.append(last_k)
        label_names.append(right_k[0])
    plt.xticks(label_k, label_names)

    plt.ylabel('Energy')
    plt.xlabel('k')
    plt.grid(True)
    plt.title('material ' + folder)
    plt.savefig('misc/'+pattern+'_search_result.png')
    plt.show() 
Example 44
Project: ONIX   Author: jlanversin   File: functions.py    MIT License 4 votes vote down vote up
def plot_selected_ratio_history(selected_list, selected_ratio_dict, history_fluence, batch_break_indexes=None):

	ratio_name_list = selected_list
	plt.style.use('dark_background')

	f, ax = plt.subplots()
	for i in range(len(ratio_name_list)):
		ratio_name = ratio_name_list[i]
		ratio = selected_ratio_dict[ratio_name]
		ax.plot(history_fluence, ratio, label = ratio_name)

	#Fluence at each batch break point
	batch_break_fluence = [history_fluence[i] for i in batch_break_indexes]
	#plt.axvline(x=0, linestyle = '--', color ='grey')
	for fluence in batch_break_fluence:
		print (fluence)
		plt.axvline(x=fluence, linestyle = '--', color ='grey')

	#quit()



	# plt.axvspan(batch_break_fluence[0], batch_break_fluence[2], alpha=0.2, color='grey')
	# plt.axvspan(batch_break_fluence[9], batch_break_fluence[12], alpha=0.2, color='grey')


	ax.set_ylabel('Ratio', fontsize=16)
	ax.set_xlabel('Fluence [cm/cm$^{3}$]', fontsize=16)
	ax.yaxis.get_offset_text().set_fontsize(16)
	ax.xaxis.get_offset_text().set_fontsize(16)
	plt.ticklabel_format(style='sci', axis='y',scilimits=(0,0))
	ax.grid(color = 'dimgray')
	plt.tick_params(labelsize=15)
	ax.set_ylim(bottom = 0, top=3.1)
	plt.legend(prop={'size': 12})

	# Put these freaking Shutdown dates on the top
	ax3 = ax.twiny()
	ax3.set_xlim(ax.get_xlim())
	ax3.set_xticks(batch_break_fluence)
	ax3.tick_params(labelsize=11)
	ax3.set_xticklabels(['Shutdown\nApril 1994', 'Shutdown\nApril 2005', 'Shutdown\nJuly 2007', 'Shutdown\nOctober 2015', 'Shutdown\nMarch 2018'])

	#ax3.set_ylim(bottom = 0, top=3.1)

	plt.show() 
Example 45
Project: neuromorphic_odour_classifier   Author: iulialexandra   File: run_eNose.py    MIT License 4 votes vote down vote up
def plot_spike_sources(filePath, fileName, nrInputNeurons, nrVR,
                         observationTime, totalSimulationTime,
                        classLabels, odourNames):
    '''Plot the Poisson spike source matrix
    Input:
        -path of the spike times file
        -name of the spike times file
        -number of input neurons (= number of sensors)
        -number of virtual receptors
        -length of the Poisson spike train for each sample
        -maximum simulation time for each recording
         (number of samples for each recording) 
         x (length of Poisson spike train for each sample)
        -class labels
        -names of the odours used
    '''
    bckndNames =[[]]*len(odourNames)
    
    spikeTimes = utils.readSpikeSourceDataFile(os.path.join(filePath,
                                                     fileName))['spike_times']
    plt.figure(figsize=(20,20))
    for idx, line in enumerate(spikeTimes):
        for x in line:
            plt.plot(x, idx, 'ko', markersize = 2)
    for j in range(idx, nrVR):
        plt.plot(0, j, 'k,')


    for j, classLabel in enumerate(classLabels):
        plt.axvspan(j*observationTime, j*observationTime+observationTime,
                     facecolor=colors[int(classLabel)], alpha=0.3)
        
    for idxO, odour in enumerate(odourNames):
        bckndNames[idxO] = mpatches.Patch(color=colors[idxO], label=odour)

    
    plt.legend(handles=bckndNames, loc ='best', prop={'size':20}) 
    plt.xlabel('Simulation time[ms]', fontsize=20)
    plt.ylabel('%i Virtual receptors per sensor'%(nrVR/nrInputNeurons),
                 fontsize=20)
    plt.tick_params(labelsize=20)
    plt.title('VR spike times for classes %s'%str(classLabels), fontsize=20)
    
    
    plt.savefig(fileName+'.pdf')

    plt.close()

#----------------------------------------------------------------------------- 
Example 46
Project: ward-metrics   Author: phev8   File: visualisations.py    MIT License 4 votes vote down vote up
def plot_events_with_segment_scores(segment_results, ground_truth_events, detected_events, use_datetime_x=False, show=True):
    """
    Test
    :param segment_results:
    :param ground_truth_events:
    :param detected_events:
    :param use_datetime_x:
    :param show:
    :return:
    """
    fig = plt.figure(figsize=(10, 3))
    a = 3

    # TODO: convert times to datetime if flag is set

    # write y axis labels for ground truth and detections
    plt.yticks([0.2, 0.5, 0.8], ["detections", "segment score", "actual events"])
    plt.ylim([0, 1])

    for d in detected_events:
        plt.axvspan(d[0], d[1], 0, 0.5)

    for gt in ground_truth_events:
        plt.axvspan(gt[0], gt[1], 0.5, 1)

    for s in segment_results:
        color = "black"
        index_of_cat = 4
        if s[index_of_cat] == "TP":
            color = "green"
        elif s[index_of_cat] == "FP":
            color = "red"
        elif s[index_of_cat] == "FN":
            color = "yellow"
        elif s[index_of_cat] == "TN":
            color = "blue"

        # TODO: format text nicely
        plt.text((s[1]+s[0])/2, 0.8, s[2], horizontalalignment='center', verticalalignment='center')
        plt.text((s[1]+s[0])/2, 0.2, s[3], horizontalalignment='center', verticalalignment='center')
        plt.text((s[1]+s[0])/2, 0.5, s[5], horizontalalignment='center', verticalalignment='center')
        plt.axvspan(s[0], s[1], 0.4, 0.6, color=color)
        plt.axvline(s[0], color="black")
        plt.axvline(s[1], color="black")

    plt.tight_layout()

    if show:
        plt.show()
    else:
        plt.draw() 
Example 47
Project: OASIS   Author: j-friedrich   File: fig2.py    GNU General Public License v3.0 4 votes vote down vote up
def cb(y, P, counter, current):
    solution = np.empty(len(y))
    for i, (v, w, f, l) in enumerate(P):
        solution[f:f + l] = (v if i else max(v, 0)) / w * g**np.arange(l)
    color = y.copy()
    ax1.plot(solution, c='k', zorder=-11, lw=1.3, clip_on=False)
    ax1.scatter(np.arange(len(y)), solution, s=40, cmap=plt.cm.Spectral,
                c=color, clip_on=False, zorder=11)
    ax1.scatter([np.arange(len(y))[current]], [solution[current]],
                s=120, lw=2.5, marker='+', color='b', clip_on=False, zorder=11)
    for a in P[::2]:
        ax1.axvspan(a[2], a[2] + a[3], alpha=0.1, color='k', zorder=-11)
    for x in np.where(trueSpikes)[0]:
        ax1.plot([x, x], [0, 2.3], lw=1.5, c='r', zorder=-12)
    ax1.set_xlim((0, len(y) - .5))
    ax1.set_ylim((0, 2.3))
    simpleaxis(ax1)
    ax1.set_xticks([])
    ax1.set_yticks([])
    ax1.set_ylabel('Fluorescence')
    for i, s in enumerate(np.r_[[0], solution[1:] - g * solution[:-1]]):
        ax2.plot([i, i], [0, s], c='k', zorder=-11, lw=1.4, clip_on=False)
    ax2.scatter(np.arange(len(y)), np.r_[[0], solution[1:] - g * solution[:-1]],
                s=40, cmap=plt.cm.Spectral, c=color, clip_on=False, zorder=11)
    ax2.scatter([np.arange(len(y))[current]],
                [np.r_[[0], solution[1:] - g * solution[:-1]][current]],
                s=120, lw=2.5, marker='+', color='b', clip_on=False, zorder=11)
    for a in P[::2]:
        ax2.axvspan(a[2], a[2] + a[3], alpha=0.1, color='k', zorder=-11)
    for x in np.where(trueSpikes)[0]:
        ax2.plot([x, x], [0, 1.55], lw=1.5, c='r', zorder=-12)
    ax2.set_xlim((0, len(y) - .5))
    ax2.set_ylim((0, 1.55))
    simpleaxis(ax2)
    ax2.set_xticks([])
    ax2.set_yticks([])
    ax2.set_xlabel('Time', labelpad=35, x=.5)
    ax2.set_ylabel('Spikes')
    plt.subplots_adjust(left=0.032, right=.995, top=.995, bottom=0.19, hspace=0.22)
    if save_figs:
        plt.savefig('video/%03d.pdf' % counter)
    plt.pause(1e-9)
    ax1.clear()
    ax2.clear()


# generate data 
Example 48
Project: SWHLab   Author: swharden   File: protocols.py    MIT License 4 votes vote down vote up
def BLS_average_stack(theABF):
    abf=ABF(theABF)
    T1,T2=abf.epochTimes(2)
    padding=.1
    if abf.units=="mV":
        padding=.25
    Tdiff=max([T2-T1,padding])
    Tdiff=min([T1,padding])
    X1,X2=T1-Tdiff,T2+Tdiff
    I1,I2=X1*abf.pointsPerSec,X2*abf.pointsPerSec

    plt.figure(figsize=(10,10))
    chunks=np.empty((int(abf.sweeps),int(I2-I1)))
    Xs=np.array(abf.sweepX2[int(I1):int(I2)])
    for sweep in abf.setsweeps():
        chunks[sweep]=abf.sweepY[int(I1):int(I2)].flatten()
        plt.subplot(211)
        plt.plot(Xs,chunks[sweep],alpha=.2,color='.5',lw=2)
        plt.subplot(212)
        if abf.units=='pA':
            plt.plot(Xs,chunks[sweep]+100*(abf.sweeps-sweep),alpha=.5,color='b',lw=2) # if VC, focus on BLS
        else:
            plt.plot(abf.sweepX2,abf.sweepY+100*(abf.sweeps-sweep),alpha=.5,color='b',lw=2) # if IC, show full sweep

    plt.subplot(211)
    plt.plot(Xs,np.average(chunks,axis=0),alpha=.5,lw=2)
    plt.title("%s.abf - BLS - average of %d sweeps"%(abf.ID,abf.sweeps))
    plt.ylabel(abf.units2)
    plt.axvspan(T1,T2,alpha=.2,color='y',lw=0)
    plt.margins(0,.1)

    plt.subplot(212)
    plt.xlabel("time (sec)")
    plt.ylabel("stacked sweeps")
    plt.axvspan(T1,T2,alpha=.2,color='y',lw=0)
    if abf.units=='mV':
        plt.axvline(T1,color='r',alpha=.2,lw=3)
#        plt.axvline(T2,color='r',alpha=.2,lw=3)
    plt.margins(0,.1)

    plt.tight_layout()
    frameAndSave(abf,"BLS","experiment")
    plt.close('all') 
Example 49
Project: SWHLab   Author: swharden   File: protocols.py    MIT License 4 votes vote down vote up
def proto_avgRange(theABF,m1=None,m2=None):
    """experiment: generic VC time course experiment."""

    abf=ABF(theABF)
    abf.log.info("analyzing as a fast IV")
    if m1 is None:
        m1=abf.sweepLength
    if m2 is None:
        m2=abf.sweepLength

    I1=int(abf.pointsPerSec*m1)
    I2=int(abf.pointsPerSec*m2)

    Ts=np.arange(abf.sweeps)*abf.sweepInterval
    Yav=np.empty(abf.sweeps)*np.nan # average
    Ysd=np.empty(abf.sweeps)*np.nan # standard deviation
    #Yar=np.empty(abf.sweeps)*np.nan # area

    for sweep in abf.setsweeps():
        Yav[sweep]=np.average(abf.sweepY[I1:I2])
        Ysd[sweep]=np.std(abf.sweepY[I1:I2])
        #Yar[sweep]=np.sum(abf.sweepY[I1:I2])/(I2*I1)-Yav[sweep]

    plot=ABFplot(abf)
    plt.figure(figsize=(SQUARESIZE*2,SQUARESIZE/2))

    plt.subplot(131)
    plot.title="first sweep"
    plot.figure_sweep(0)
    plt.title("First Sweep\n(shaded measurement range)")
    plt.axvspan(m1,m2,color='r',ec=None,alpha=.1)

    plt.subplot(132)
    plt.grid(alpha=.5)
    for i,t in enumerate(abf.comment_times):
        plt.axvline(t/60,color='r',alpha=.5,lw=2,ls='--')
    plt.plot(Ts/60,Yav,'.',alpha=.75)
    plt.title("Range Average\nTAGS: %s"%(", ".join(abf.comment_tags)))
    plt.ylabel(abf.units2)
    plt.xlabel("minutes")
    plt.margins(0,.1)

    plt.subplot(133)
    plt.grid(alpha=.5)
    for i,t in enumerate(abf.comment_times):
        plt.axvline(t/60,color='r',alpha=.5,lw=2,ls='--')
    plt.plot(Ts/60,Ysd,'.',alpha=.5,color='g',ms=15,mew=0)
    #plt.fill_between(Ts/60,Ysd*0,Ysd,lw=0,alpha=.5,color='g')
    plt.title("Range Standard Deviation\nTAGS: %s"%(", ".join(abf.comment_tags)))
    plt.ylabel(abf.units2)
    plt.xlabel("minutes")
    plt.margins(0,.1)
    plt.axis([None,None,0,np.percentile(Ysd,99)*1.25])

    plt.tight_layout()
    frameAndSave(abf,"sweep vs average","experiment")
    plt.close('all') 
Example 50
Project: pyABFauto   Author: swharden   File: analysisByProtocol.py    MIT License 4 votes vote down vote up
def generic_ap_steps(abf):
    """Create a plot for generic AP steps."""
    log.debug("generic plot: AP steps")
    assert isinstance(abf, pyabf.ABF)
    plotFigNew(abf)

    # all sweeps overlayed
    axOvr = plt.gcf().add_subplot(2, 2, 1)
    pyabf.plot.sweeps(abf, axis=axOvr, alpha=.5)
    axOvr.set_title(f"Sweep Overlay")

    # all sweeps stacked
    axStack = plt.gcf().add_subplot(2, 2, 2)
    pyabf.plot.sweeps(abf, axis=axStack, alpha=.5, offsetYunits=100)
    axStack.set_title(f"Sweeps Stacked")

    # first sweep with APs
    axAp = plt.gcf().add_subplot(2, 2, 3)
    p1, p2 = _secLookUp(abf, 0, 1, True)
    for sweep in abf.sweepList:
        abf.setSweep(sweep)
        if np.max(abf.sweepY[p1:p2]) > 10:
            break
    pyabf.plot.sweeps(abf, sweepNumbers=[abf.sweepNumber], axis=axAp, alpha=1)
    axAp.axis([p1/abf.dataRate, p2/abf.dataRate, None, None])
    axAp.set_title(f"First Action Potential")

    # AP gain curve
    axGain = plt.gcf().add_subplot(2, 2, 4)

    for epochNumber, color in zip([1, 4], ['C0', 'C1']):
        if epochNumber >= len(pyabf.stimulus.epochValues(abf)[0]):
            continue
        currents = pyabf.stimulus.epochValues(abf)[:, epochNumber]
        epochSec1 = pyabf.stimulus.epochPoints(abf)[epochNumber]/abf.dataRate
        epochSec2 = pyabf.stimulus.epochPoints(abf)[epochNumber+1]/abf.dataRate
        [apFreqInBin, apFreqFirst] = pyabf.ap.ap_freq_per_sweep(
            abf, epochNumber)
        axGain.plot(currents, apFreqInBin, '.-', color=color)
        axGain.plot(currents, apFreqFirst, '.:', color=color)
        axStack.axvspan(epochSec1, epochSec2, color=color, alpha=.1)
    axGain.set_title(f"AP Gain Curve")
    axGain.set_ylabel("AP Frequency (Hz)")
    axGain.set_xlabel("Applied Current (pA)")
    axGain.axhline(40, color='r', alpha=.2, ls='--', lw=2)
    plotFigSave(abf, tag="generic-overlay", labelAxes=False)