Python matplotlib.pyplot.eventplot() Examples

The following are 22 code examples of matplotlib.pyplot.eventplot(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: run.py    From yass with Apache License 2.0 6 votes vote down vote up
def make_raster_plot(self):
        
        fname = os.path.join(self.save_dir, 'raster.png')
        if os.path.exists(fname):
            return
        
        plt.figure(figsize=(30,15))
        ptps = self.ptps
        order = np.argsort(ptps)
        sorted_ptps = np.round(np.sort(ptps),2)
        for j in range(self.n_units):
            k = order[j]
            idx = self.spike_train[:,1] == k
            spt = self.spike_train[idx, 0]/self.sampling_rate
            prob = self.soft_assignment[idx]
            if np.sum(prob) > 1:
                spt = np.sort(np.random.choice(
                    spt, int(np.sum(prob)), False, prob/np.sum(prob)))
                plt.eventplot(spt, lineoffsets=j, color='k', linewidths=0.01)
        plt.yticks(np.arange(0,self.n_units,10), sorted_ptps[0:self.n_units:10])
        plt.ylabel('ptps', fontsize=self.fontsize)
        plt.xlabel('time (seconds)', fontsize=self.fontsize)
        plt.title('Raster Plot Sorted by PTP', fontsize=self.fontsize)
        plt.savefig(fname, bbox_inches='tight', dpi=100)
        plt.close() 
Example #2
Source File: test_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_eventplot_colors(colors):
    '''Test the *colors* parameter of eventplot. Inspired by the issue #8193.
    '''
    data = [[i] for i in range(4)]  # 4 successive events of different nature

    # Build the list of the expected colors
    expected = [c if c is not None else 'C0' for c in colors]
    # Convert the list into an array of RGBA values
    # NB: ['rgbk'] is not a valid argument for to_rgba_array, while 'rgbk' is.
    if len(expected) == 1:
        expected = expected[0]
    expected = np.broadcast_to(mcolors.to_rgba_array(expected), (len(data), 4))

    fig, ax = plt.subplots()
    if len(colors) == 1:  # tuple with a single string (like '0.5' or 'rgbk')
        colors = colors[0]
    collections = ax.eventplot(data, colors=colors)

    for coll, color in zip(collections, expected):
        assert_allclose(coll.get_color(), color) 
Example #3
Source File: test_axes.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def test_eventplot_colors(colors):
    '''Test the *colors* parameter of eventplot. Inspired by the issue #8193.
    '''
    data = [[i] for i in range(4)]  # 4 successive events of different nature

    # Build the list of the expected colors
    expected = [c if c is not None else 'C0' for c in colors]
    # Convert the list into an array of RGBA values
    # NB: ['rgbk'] is not a valid argument for to_rgba_array, while 'rgbk' is.
    if len(expected) == 1:
        expected = expected[0]
    expected = broadcast_to(mcolors.to_rgba_array(expected), (len(data), 4))

    fig, ax = plt.subplots()
    if len(colors) == 1:  # tuple with a single string (like '0.5' or 'rgbk')
        colors = colors[0]
    collections = ax.eventplot(data, colors=colors)

    for coll, color in zip(collections, expected):
        assert_allclose(coll.get_color(), color) 
Example #4
Source File: test_axes.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_eventplot_colors(colors):
    '''Test the *colors* parameter of eventplot. Inspired by the issue #8193.
    '''
    data = [[i] for i in range(4)]  # 4 successive events of different nature

    # Build the list of the expected colors
    expected = [c if c is not None else 'C0' for c in colors]
    # Convert the list into an array of RGBA values
    # NB: ['rgbk'] is not a valid argument for to_rgba_array, while 'rgbk' is.
    if len(expected) == 1:
        expected = expected[0]
    expected = np.broadcast_to(mcolors.to_rgba_array(expected), (len(data), 4))

    fig, ax = plt.subplots()
    if len(colors) == 1:  # tuple with a single string (like '0.5' or 'rgbk')
        colors = colors[0]
    collections = ax.eventplot(data, colors=colors)

    for coll, color in zip(collections, expected):
        assert_allclose(coll.get_color(), color) 
Example #5
Source File: test_axes.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_eventplot_problem_kwargs():
    '''
    test that 'singular' versions of LineCollection props raise an
    IgnoredKeywordWarning rather than overriding the 'plural' versions (e.g.
    to prevent 'color' from overriding 'colors', see issue #4297)
    '''
    np.random.seed(0)

    data1 = np.random.random([20]).tolist()
    data2 = np.random.random([10]).tolist()
    data = [data1, data2]

    fig = plt.figure()
    axobj = fig.add_subplot(111)

    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        colls = axobj.eventplot(data,
                                colors=['r', 'b'],
                                color=['c', 'm'],
                                linewidths=[2, 1],
                                linewidth=[1, 2],
                                linestyles=['solid', 'dashed'],
                                linestyle=['dashdot', 'dotted'])

        # check that three IgnoredKeywordWarnings were raised
        assert len(w) == 3
        assert all(issubclass(wi.category, IgnoredKeywordWarning) for wi in w) 
Example #6
Source File: run.py    From yass with Apache License 2.0 5 votes vote down vote up
def add_ptp_vs_time(self, ptp, spt, template):

        plt.scatter(spt, ptp/self.sampling_rate, c='k')
        plt.plot([np.min(spt), np.max(spt)], [temp.ptp(), temp.ptp()], 'r')

        #plt.eventplot(spt, color='k', linewidths=0.01)
        plt.title('ptp vs spike times (red = template ptp)',
                  fontsize=self.fontsize)
        
        return gs 
Example #7
Source File: test_axes.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_eventplot_legend():
    plt.eventplot([1.0], label='Label')
    plt.legend() 
Example #8
Source File: test_axes.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_empty_eventplot():
    fig, ax = plt.subplots(1, 1)
    ax.eventplot([[]], colors=[(0.0, 0.0, 0.0, 0.0)])
    plt.draw() 
Example #9
Source File: test_axes.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_eventplot_problem_kwargs():
    '''
    test that 'singular' versions of LineCollection props raise an
    IgnoredKeywordWarning rather than overriding the 'plural' versions (e.g.
    to prevent 'color' from overriding 'colors', see issue #4297)
    '''
    np.random.seed(0)

    data1 = np.random.random([20]).tolist()
    data2 = np.random.random([10]).tolist()
    data = [data1, data2]

    fig = plt.figure()
    axobj = fig.add_subplot(111)

    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        colls = axobj.eventplot(data,
                                colors=['r', 'b'],
                                color=['c', 'm'],
                                linewidths=[2, 1],
                                linewidth=[1, 2],
                                linestyles=['solid', 'dashed'],
                                linestyle=['dashdot', 'dotted'])

        # check that three IgnoredKeywordWarnings were raised
        assert len(w) == 3
        assert all(issubclass(wi.category, IgnoredKeywordWarning) for wi in w) 
Example #10
Source File: test_axes.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_eventplot_defaults():
    '''
    test that eventplot produces the correct output given the default params
    (see bug #3728)
    '''
    np.random.seed(0)

    data1 = np.random.random([32, 20]).tolist()
    data2 = np.random.random([6, 20]).tolist()
    data = data1 + data2

    fig = plt.figure()
    axobj = fig.add_subplot(111)
    colls = axobj.eventplot(data) 
Example #11
Source File: test_axes.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_eventplot_legend():
    plt.eventplot([1.0], label='Label')
    plt.legend() 
Example #12
Source File: test_axes.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_empty_eventplot():
    fig, ax = plt.subplots(1, 1)
    ax.eventplot([[]], colors=[(0.0, 0.0, 0.0, 0.0)])
    plt.draw() 
Example #13
Source File: test_axes.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_eventplot_defaults():
    '''
    test that eventplot produces the correct output given the default params
    (see bug #3728)
    '''
    np.random.seed(0)

    data1 = np.random.random([32, 20]).tolist()
    data2 = np.random.random([6, 20]).tolist()
    data = data1 + data2

    fig = plt.figure()
    axobj = fig.add_subplot(111)
    colls = axobj.eventplot(data) 
Example #14
Source File: test_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_eventplot_legend():
    plt.eventplot([1.0], label='Label')
    plt.legend() 
Example #15
Source File: test_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_empty_eventplot():
    fig, ax = plt.subplots(1, 1)
    ax.eventplot([[]], colors=[(0.0, 0.0, 0.0, 0.0)])
    plt.draw() 
Example #16
Source File: test_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_eventplot_problem_kwargs():
    '''
    test that 'singular' versions of LineCollection props raise an
    IgnoredKeywordWarning rather than overriding the 'plural' versions (e.g.
    to prevent 'color' from overriding 'colors', see issue #4297)
    '''
    np.random.seed(0)

    data1 = np.random.random([20]).tolist()
    data2 = np.random.random([10]).tolist()
    data = [data1, data2]

    fig = plt.figure()
    axobj = fig.add_subplot(111)

    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        colls = axobj.eventplot(data,
                                colors=['r', 'b'],
                                color=['c', 'm'],
                                linewidths=[2, 1],
                                linewidth=[1, 2],
                                linestyles=['solid', 'dashed'],
                                linestyle=['dashdot', 'dotted'])

        # check that three IgnoredKeywordWarnings were raised
        assert len(w) == 3
        assert all(issubclass(wi.category, IgnoredKeywordWarning) for wi in w) 
Example #17
Source File: test_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_eventplot_defaults():
    '''
    test that eventplot produces the correct output given the default params
    (see bug #3728)
    '''
    np.random.seed(0)

    data1 = np.random.random([32, 20]).tolist()
    data2 = np.random.random([6, 20]).tolist()
    data = data1 + data2

    fig = plt.figure()
    axobj = fig.add_subplot(111)
    colls = axobj.eventplot(data) 
Example #18
Source File: test_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_eventplot():
    '''
    test that eventplot produces the correct output
    '''
    np.random.seed(0)

    data1 = np.random.random([32, 20]).tolist()
    data2 = np.random.random([6, 20]).tolist()
    data = data1 + data2
    num_datasets = len(data)

    colors1 = [[0, 1, .7]] * len(data1)
    colors2 = [[1, 0, 0],
               [0, 1, 0],
               [0, 0, 1],
               [1, .75, 0],
               [1, 0, 1],
               [0, 1, 1]]
    colors = colors1 + colors2

    lineoffsets1 = 12 + np.arange(0, len(data1)) * .33
    lineoffsets2 = [-15, -3, 1, 1.5, 6, 10]
    lineoffsets = lineoffsets1.tolist() + lineoffsets2

    linelengths1 = [.33] * len(data1)
    linelengths2 = [5, 2, 1, 1, 3, 1.5]
    linelengths = linelengths1 + linelengths2

    fig = plt.figure()
    axobj = fig.add_subplot(111)
    colls = axobj.eventplot(data, colors=colors, lineoffsets=lineoffsets,
                            linelengths=linelengths)

    num_collections = len(colls)
    assert num_collections == num_datasets

    # Reuse testcase from above for a labeled data test
    data = {"pos": data, "c": colors, "lo": lineoffsets, "ll": linelengths}
    fig = plt.figure()
    axobj = fig.add_subplot(111)
    colls = axobj.eventplot("pos", colors="c", lineoffsets="lo",
                            linelengths="ll", data=data)
    num_collections = len(colls)
    assert num_collections == num_datasets 
Example #19
Source File: test_axes.py    From twitter-stock-recommendation with MIT License 4 votes vote down vote up
def test_eventplot():
    '''
    test that eventplot produces the correct output
    '''
    np.random.seed(0)

    data1 = np.random.random([32, 20]).tolist()
    data2 = np.random.random([6, 20]).tolist()
    data = data1 + data2
    num_datasets = len(data)

    colors1 = [[0, 1, .7]] * len(data1)
    colors2 = [[1, 0, 0],
               [0, 1, 0],
               [0, 0, 1],
               [1, .75, 0],
               [1, 0, 1],
               [0, 1, 1]]
    colors = colors1 + colors2

    lineoffsets1 = 12 + np.arange(0, len(data1)) * .33
    lineoffsets2 = [-15, -3, 1, 1.5, 6, 10]
    lineoffsets = lineoffsets1.tolist() + lineoffsets2

    linelengths1 = [.33] * len(data1)
    linelengths2 = [5, 2, 1, 1, 3, 1.5]
    linelengths = linelengths1 + linelengths2

    fig = plt.figure()
    axobj = fig.add_subplot(111)
    colls = axobj.eventplot(data, colors=colors, lineoffsets=lineoffsets,
                            linelengths=linelengths)

    num_collections = len(colls)
    assert num_collections == num_datasets

    # Reuse testcase from above for a labeled data test
    data = {"pos": data, "c": colors, "lo": lineoffsets, "ll": linelengths}
    fig = plt.figure()
    axobj = fig.add_subplot(111)
    colls = axobj.eventplot("pos", colors="c", lineoffsets="lo",
                            linelengths="ll", data=data)
    num_collections = len(colls)
    assert num_collections == num_datasets 
Example #20
Source File: test_axes.py    From coffeegrindsize with MIT License 4 votes vote down vote up
def test_eventplot():
    '''
    test that eventplot produces the correct output
    '''
    np.random.seed(0)

    data1 = np.random.random([32, 20]).tolist()
    data2 = np.random.random([6, 20]).tolist()
    data = data1 + data2
    num_datasets = len(data)

    colors1 = [[0, 1, .7]] * len(data1)
    colors2 = [[1, 0, 0],
               [0, 1, 0],
               [0, 0, 1],
               [1, .75, 0],
               [1, 0, 1],
               [0, 1, 1]]
    colors = colors1 + colors2

    lineoffsets1 = 12 + np.arange(0, len(data1)) * .33
    lineoffsets2 = [-15, -3, 1, 1.5, 6, 10]
    lineoffsets = lineoffsets1.tolist() + lineoffsets2

    linelengths1 = [.33] * len(data1)
    linelengths2 = [5, 2, 1, 1, 3, 1.5]
    linelengths = linelengths1 + linelengths2

    fig = plt.figure()
    axobj = fig.add_subplot(111)
    colls = axobj.eventplot(data, colors=colors, lineoffsets=lineoffsets,
                            linelengths=linelengths)

    num_collections = len(colls)
    assert num_collections == num_datasets

    # Reuse testcase from above for a labeled data test
    data = {"pos": data, "c": colors, "lo": lineoffsets, "ll": linelengths}
    fig = plt.figure()
    axobj = fig.add_subplot(111)
    colls = axobj.eventplot("pos", colors="c", lineoffsets="lo",
                            linelengths="ll", data=data)
    num_collections = len(colls)
    assert num_collections == num_datasets 
Example #21
Source File: visualization.py    From bindsnet with GNU Affero General Public License v3.0 4 votes vote down vote up
def plot_spike_trains_for_example(
    spikes: torch.Tensor,
    n_ex: Optional[int] = None,
    top_k: Optional[int] = None,
    indices: Optional[List[int]] = None,
) -> None:
    # language=rst
    """
    Plot spike trains for top-k neurons or for specific indices.

    :param spikes: Spikes for one simulation run of shape
        ``(n_examples, n_neurons, time)``.
    :param n_ex: Allows user to pick which example to plot spikes for.
    :param top_k: Plot k neurons that spiked the most for n_ex example.
    :param indices: Plot specific neurons' spiking activity instead of top_k.
    """
    assert n_ex is not None and 0 <= n_ex < spikes.shape[0]

    plt.figure()

    if top_k is None and indices is None:  # Plot all neurons' spiking activity
        spike_per_neuron = [
            np.argwhere(i == 1).flatten() for i in spikes[n_ex, :, :]
        ]
        plt.title("Spiking activity for all %d neurons" % spikes.shape[1])

    elif top_k is None:  # Plot based on indices parameter
        assert indices is not None
        spike_per_neuron = [
            np.argwhere(i == 1).flatten() for i in spikes[n_ex, indices, :]
        ]

    elif indices is None:  # Plot based on top_k parameter
        assert top_k is not None
        # Obtain the top k neurons that fired the most
        top_k_loc = np.argsort(np.sum(spikes[n_ex, :, :], axis=1), axis=0)[
            ::-1
        ]
        spike_per_neuron = [
            np.argwhere(i == 1).flatten()
            for i in spikes[n_ex, top_k_loc[0:top_k], :]
        ]
        plt.title("Spiking activity for top %d neurons" % top_k)

    else:
        raise ValueError('One of "top_k" or "indices" or both must be None')

    plt.eventplot(spike_per_neuron, linelengths=[0.5] * len(spike_per_neuron))
    plt.xlabel("Simulation Time")
    plt.ylabel("Neuron index")
    plt.show() 
Example #22
Source File: visualization.py    From bindsnet with GNU Affero General Public License v3.0 4 votes vote down vote up
def plot_spike_trains_for_example(
    spikes: torch.Tensor,
    n_ex: Optional[int] = None,
    top_k: Optional[int] = None,
    indices: Optional[List[int]] = None,
) -> None:
    # language=rst
    """
    Plot spike trains for top-k neurons or for specific indices.

    :param spikes: Spikes for one simulation run of shape
        ``(n_examples, n_neurons, time)``.
    :param n_ex: Allows user to pick which example to plot spikes for.
    :param top_k: Plot k neurons that spiked the most for n_ex example.
    :param indices: Plot specific neurons' spiking activity instead of top_k.
    """
    assert n_ex is not None and 0 <= n_ex < spikes.shape[0]

    plt.figure()

    if top_k is None and indices is None:  # Plot all neurons' spiking activity
        spike_per_neuron = [np.argwhere(i == 1).flatten() for i in spikes[n_ex, :, :]]
        plt.title("Spiking activity for all %d neurons" % spikes.shape[1])

    elif top_k is None:  # Plot based on indices parameter
        assert indices is not None
        spike_per_neuron = [
            np.argwhere(i == 1).flatten() for i in spikes[n_ex, indices, :]
        ]

    elif indices is None:  # Plot based on top_k parameter
        assert top_k is not None
        # Obtain the top k neurons that fired the most
        top_k_loc = np.argsort(np.sum(spikes[n_ex, :, :], axis=1), axis=0)[::-1]
        spike_per_neuron = [
            np.argwhere(i == 1).flatten() for i in spikes[n_ex, top_k_loc[0:top_k], :]
        ]
        plt.title("Spiking activity for top %d neurons" % top_k)

    else:
        raise ValueError('One of "top_k" or "indices" or both must be None')

    plt.eventplot(spike_per_neuron, linelengths=[0.5] * len(spike_per_neuron))
    plt.xlabel("Simulation Time")
    plt.ylabel("Neuron index")
    plt.show()