EVENTPLOT

Excel Usage

=EVENTPLOT(data, title, xlabel, ylabel, stat_color, event_orientation, legend)
  • data (list[list], required): Input data.
  • title (str, optional, default: null): Chart title.
  • xlabel (str, optional, default: null): Label for X-axis.
  • ylabel (str, optional, default: null): Label for Y-axis.
  • stat_color (str, optional, default: null): Event color.
  • event_orientation (str, optional, default: “horizontal”): Orientation (‘horizontal’ or ‘vertical’).
  • legend (str, optional, default: “false”): Show legend.

Returns (object): Matplotlib Figure object (standard Python) or base64 encoded PNG string (Pyodide).

Examples

Example 1: Event plot with single sequence

Inputs:

data
1
2
3
4
5

Excel formula:

=EVENTPLOT({1;2;3;4;5})

Expected output:

"chart"

Example 2: Event plot with multiple sequences

Inputs:

data
1 1.5 2
2 2.5 3
3 3.5 4
4 4.5 5

Excel formula:

=EVENTPLOT({1,1.5,2;2,2.5,3;3,3.5,4;4,4.5,5})

Expected output:

"chart"

Example 3: Vertical event plot with labels

Inputs:

data event_orientation title xlabel ylabel
1 vertical Test Event Plot Time Events
2
3
4
5

Excel formula:

=EVENTPLOT({1;2;3;4;5}, "vertical", "Test Event Plot", "Time", "Events")

Expected output:

"chart"

Example 4: Event plot with custom color

Inputs:

data stat_color
1 1.5 red
2 2.5
3 3.5

Excel formula:

=EVENTPLOT({1,1.5;2,2.5;3,3.5}, "red")

Expected output:

"chart"

Python Code

import sys
import matplotlib
IS_PYODIDE = sys.platform == "emscripten"
if IS_PYODIDE:
    matplotlib.use('Agg')
import matplotlib.pyplot as plt
import io
import base64
import numpy as np

def eventplot(data, title=None, xlabel=None, ylabel=None, stat_color=None, event_orientation='horizontal', legend='false'):
    """
    Create a spike raster or event plot from data.

    See: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.eventplot.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        data (list[list]): Input data.
        title (str, optional): Chart title. Default is None.
        xlabel (str, optional): Label for X-axis. Default is None.
        ylabel (str, optional): Label for Y-axis. Default is None.
        stat_color (str, optional): Event color. Valid options: Blue, Green, Red, Cyan, Magenta, Yellow, Black, White. Default is None.
        event_orientation (str, optional): Orientation ('horizontal' or 'vertical'). Valid options: Horizontal, Vertical. Default is 'horizontal'.
        legend (str, optional): Show legend. Valid options: True, False. Default is 'false'.

    Returns:
        object: Matplotlib Figure object (standard Python) or base64 encoded PNG string (Pyodide).
    """
    def to2d(x):
        return [[x]] if not isinstance(x, list) else x

    def str_to_bool(s):
        return s.lower() == "true" if isinstance(s, str) else bool(s)

    try:
        data = to2d(data)

        if not isinstance(data, list) or not all(isinstance(row, list) for row in data):
            return "Error: Invalid input - data must be a 2D list"

        # Extract numeric columns
        cols = []
        max_rows = max(len(row) for row in data) if data else 0

        for col_idx in range(max_rows):
            col_data = []
            for row in data:
                if col_idx < len(row):
                    val = row[col_idx]
                    try:
                        col_data.append(float(val))
                    except (TypeError, ValueError):
                        continue
            if col_data:
                cols.append(col_data)

        if not cols:
            return "Error: No valid numeric data found"

        # Create plot
        fig, ax = plt.subplots(figsize=(8, 6))

        # Plot eventplot
        color = stat_color if stat_color else None
        colors = [color] * len(cols) if color else None

        # Map orientation values
        orient_map = {'horizontal': 'horizontal', 'vertical': 'vertical'}
        plot_orientation = orient_map.get(event_orientation, 'horizontal')

        ax.eventplot(cols, orientation=plot_orientation, colors=colors,
                    lineoffsets=np.arange(1, len(cols) + 1),
                    linelengths=0.5)

        if title:
            ax.set_title(title)
        if xlabel:
            ax.set_xlabel(xlabel)
        if ylabel:
            ax.set_ylabel(ylabel)

        if str_to_bool(legend) and len(cols) > 1:
            ax.legend([f'Sequence {i+1}' for i in range(len(cols))])

        plt.tight_layout()

        # Return based on platform
        if IS_PYODIDE:
            buf = io.BytesIO()
            plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
            buf.seek(0)
            img_base64 = base64.b64encode(buf.read()).decode('utf-8')
            plt.close(fig)
            return f"data:image/png;base64,{img_base64}"
        else:
            return fig
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator