ERRORBAR

Excel Usage

=ERRORBAR(data, title, xlabel, ylabel, stat_color, fmt, capsize, grid, 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): Color for lines and markers.
  • fmt (str, optional, default: “o”): Format string (e.g., ‘o’ for points, ‘-’ for lines).
  • capsize (float, optional, default: 3): Size of error bar caps.
  • grid (str, optional, default: “true”): Show grid lines.
  • legend (str, optional, default: “false”): Show legend.

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

Examples

Example 1: Error bar plot with X and Y data only

Inputs:

data
1 2
2 4
3 5
4 7
5 9

Excel formula:

=ERRORBAR({1,2;2,4;3,5;4,7;5,9})

Expected output:

"chart"

Example 2: Error bar plot with Y error values

Inputs:

data
1 2 0.5
2 4 0.3
3 5 0.4
4 7 0.6
5 9 0.2

Excel formula:

=ERRORBAR({1,2,0.5;2,4,0.3;3,5,0.4;4,7,0.6;5,9,0.2})

Expected output:

"chart"

Example 3: Error bar plot with custom labels and format

Inputs:

data title xlabel ylabel fmt
1 2 0.5 Test Error Bar X Y -s
2 4 0.3
3 5 0.4

Excel formula:

=ERRORBAR({1,2,0.5;2,4,0.3;3,5,0.4}, "Test Error Bar", "X", "Y", "-s")

Expected output:

"chart"

Example 4: Error bar plot with larger cap size

Inputs:

data capsize
1 2 0.5 10
2 4 0.3
3 5 0.4

Excel formula:

=ERRORBAR({1,2,0.5;2,4,0.3;3,5,0.4}, 10)

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 errorbar(data, title=None, xlabel=None, ylabel=None, stat_color=None, fmt='o', capsize=3, grid='true', legend='false'):
    """
    Create an XY plot with error bars.

    See: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.errorbar.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): Color for lines and markers. Valid options: Blue, Green, Red, Cyan, Magenta, Yellow, Black, White. Default is None.
        fmt (str, optional): Format string (e.g., 'o' for points, '-' for lines). Default is 'o'.
        capsize (float, optional): Size of error bar caps. Default is 3.
        grid (str, optional): Show grid lines. Valid options: True, False. Default is 'true'.
        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 columns
        max_rows = max(len(row) for row in data) if data else 0

        if max_rows < 2:
            return "Error: Data must have at least 2 columns (X and Y)"

        x_data = []
        y_data = []
        yerr_data = []

        for row in data:
            if len(row) >= 2:
                try:
                    x_data.append(float(row[0]))
                    y_data.append(float(row[1]))
                    if len(row) >= 3:
                        yerr_data.append(float(row[2]))
                except (TypeError, ValueError):
                    continue

        if not x_data or not y_data:
            return "Error: No valid numeric data found in X and Y columns"

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

        # Plot errorbar
        yerr = yerr_data if yerr_data else None
        color = stat_color if stat_color else None

        ax.errorbar(x_data, y_data, yerr=yerr, fmt=fmt, 
                   color=color, capsize=capsize, label='Data' if str_to_bool(legend) else None)

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

        if str_to_bool(grid):
            ax.grid(True, alpha=0.3)

        if str_to_bool(legend):
            ax.legend()

        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