BAR

Excel Usage

=BAR(data, title, xlabel, ylabel, bar_color, orient, grid, legend)
  • data (list[list], required): Input data. Supports single column or multiple columns (Labels, Val1, Val2…).
  • 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.
  • bar_color (str, optional, default: null): Bar color.
  • orient (str, optional, default: “v”): Orientation (‘v’ for vertical, ‘h’ for horizontal).
  • 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: Simple vertical bar chart with labels

Inputs:

data
1 10
2 20
3 15
4 25

Excel formula:

=BAR({1,10;2,20;3,15;4,25})

Expected output:

"chart"

Example 2: Horizontal bar chart with title and labels

Inputs:

data title xlabel ylabel orient
1 10 Sales Data Sales Category h
2 20
3 15

Excel formula:

=BAR({1,10;2,20;3,15}, "Sales Data", "Sales", "Category", "h")

Expected output:

"chart"

Example 3: Multiple series with legend

Inputs:

data legend
1 10 15 true
2 20 25
3 15 30

Excel formula:

=BAR({1,10,15;2,20,25;3,15,30}, "true")

Expected output:

"chart"

Example 4: Colored bars with grid

Inputs:

data bar_color grid
1 10 blue true
2 20
3 15

Excel formula:

=BAR({1,10;2,20;3,15}, "blue", "true")

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 bar(data, title=None, xlabel=None, ylabel=None, bar_color=None, orient='v', grid='true', legend='false'):
    """
    Create a bar chart (vertical or horizontal) from data.

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

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

    Args:
        data (list[list]): Input data. Supports single column or multiple columns (Labels, Val1, Val2...).
        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.
        bar_color (str, optional): Bar color. Valid options: Blue, Green, Red, Cyan, Magenta, Yellow, Black, White. Default is None.
        orient (str, optional): Orientation ('v' for vertical, 'h' for horizontal). Valid options: Vertical, Horizontal. Default is 'v'.
        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).
    """
    try:
        if not isinstance(data, list) or not data or not isinstance(data[0], list):
            return "Error: Input data must be a 2D list."

        # Convert to numpy array
        try:
            arr = np.array(data, dtype=float)
        except Exception:
            return "Error: Data must be numeric."

        if arr.ndim != 2:
            return "Error: Data must be 2D."

        # Handle different column patterns
        num_cols = arr.shape[1]

        if num_cols == 1:
            # Single column: values only
            values = arr[:, 0]
            labels = np.arange(len(values))
            series = [values]
            series_names = None
        elif num_cols == 2:
            # Two columns: labels, values
            labels = arr[:, 0]
            values = arr[:, 1]
            series = [values]
            series_names = None
        else:
            # 3+ columns: labels, val1, val2, ...
            labels = arr[:, 0]
            series = [arr[:, i] for i in range(1, num_cols)]
            series_names = [f"Series {i}" for i in range(1, num_cols)]

        # Create figure
        fig, ax = plt.subplots(figsize=(6, 4))

        # Plot bars
        if orient == 'v':
            # Vertical bars
            if len(series) == 1:
                ax.bar(labels, series[0], color=bar_color if bar_color else None)
            else:
                x = np.arange(len(labels))
                for i, s in enumerate(series):
                    ax.bar(x, s, label=series_names[i] if series_names else None)
                ax.set_xticks(x)
                ax.set_xticklabels(labels)
        else:
            # Horizontal bars
            if len(series) == 1:
                ax.barh(labels, series[0], color=bar_color if bar_color else None)
            else:
                y = np.arange(len(labels))
                for i, s in enumerate(series):
                    ax.barh(y, s, label=series_names[i] if series_names else None)
                ax.set_yticks(y)
                ax.set_yticklabels(labels)

        # Set labels and title
        if title:
            ax.set_title(title)
        if xlabel:
            ax.set_xlabel(xlabel)
        if ylabel:
            ax.set_ylabel(ylabel)

        # Grid and legend
        if grid == "true":
            ax.grid(True, alpha=0.3)
        if legend == "true" and series_names:
            ax.legend()

        plt.tight_layout()

        if IS_PYODIDE:
            buf = io.BytesIO()
            plt.savefig(buf, format='png')
            plt.close(fig)
            buf.seek(0)
            img_bytes = buf.read()
            img_b64 = base64.b64encode(img_bytes).decode('utf-8')
            return f"data:image/png;base64,{img_b64}"
        else:
            return fig
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator