STEM

Excel Usage

=STEM(data, title, xlabel, ylabel, plot_color, orientation, bottom, 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.
  • plot_color (str, optional, default: null): Stem color.
  • orientation (str, optional, default: “v”): Orientation (‘v’ or ‘h’).
  • bottom (float, optional, default: 0): Baseline position.
  • 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 stem plot

Inputs:

data
1 10
2 15
3 7
4 20
5 12

Excel formula:

=STEM({1,10;2,15;3,7;4,20;5,12})

Expected output:

"chart"

Example 2: Horizontal stem plot with labels

Inputs:

data orientation title xlabel ylabel
1 5 h Horizontal Stem Values Categories
2 8
3 3
4 12

Excel formula:

=STEM({1,5;2,8;3,3;4,12}, "h", "Horizontal Stem", "Values", "Categories")

Expected output:

"chart"

Example 3: Colored stem plot with custom baseline

Inputs:

data plot_color bottom
1 -2 red 0
2 3
3 -1
4 5

Excel formula:

=STEM({1,-2;2,3;3,-1;4,5}, "red", 0)

Expected output:

"chart"

Example 4: Stem plot with legend

Inputs:

data legend plot_color
0 0 true green
1 1
2 4
3 9

Excel formula:

=STEM({0,0;1,1;2,4;3,9}, "true", "green")

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 stem(data, title=None, xlabel=None, ylabel=None, plot_color=None, orientation='v', bottom=0, legend='false'):
    """
    Create a stem/lollipop plot from data.

    See: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.stem.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.
        plot_color (str, optional): Stem color. Valid options: Blue, Green, Red, Cyan, Magenta, Yellow, Black, White. Default is None.
        orientation (str, optional): Orientation ('v' or 'h'). Valid options: Vertical, Horizontal. Default is 'v'.
        bottom (float, optional): Baseline position. Default is 0.
        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

    try:
        data = to2d(data)

        if not isinstance(data, list) or len(data) < 1:
            return "Error: Data must be a non-empty list"

        # Extract x and y values
        x_vals = []
        y_vals = []
        for row in data:
            if not isinstance(row, list) or len(row) < 2:
                continue
            try:
                x_vals.append(float(row[0]))
                y_vals.append(float(row[1]))
            except (ValueError, TypeError):
                continue

        if len(x_vals) == 0 or len(y_vals) == 0:
            return "Error: No valid data rows found"

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

        # Create stem plot
        if orientation == "v":
            markerline, stemlines, baseline = ax.stem(x_vals, y_vals, bottom=bottom)
        else:  # horizontal
            markerline, stemlines, baseline = ax.stem(y_vals, x_vals, bottom=bottom, orientation='horizontal')

        # Set color if specified
        if plot_color:
            markerline.set_color(plot_color)
            stemlines.set_color(plot_color)

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

        # Handle legend
        if legend == "true":
            ax.legend(['Data'], loc="best")

        plt.tight_layout()

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

Online Calculator