{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Multicolored lines\n\nThe example shows two ways to plot a line with the a varying color defined by\na third value. The first example defines the color at each (x, y) point.\nThe second example defines the color between pairs of points, so the length\nof the color value list is one less than the length of the x and y lists.\n\n## Color values at points\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import warnings\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.collections import LineCollection\n\n\ndef colored_line(x, y, c, ax=None, **lc_kwargs):\n    \"\"\"\n    Plot a line with a color specified along the line by a third value.\n\n    It does this by creating a collection of line segments. Each line segment is\n    made up of two straight lines each connecting the current (x, y) point to the\n    midpoints of the lines connecting the current point with its two neighbors.\n    This creates a smooth line with no gaps between the line segments.\n\n    Parameters\n    ----------\n    x, y : array-like\n        The horizontal and vertical coordinates of the data points.\n    c : array-like\n        The color values, which should be the same size as x and y.\n    ax : matplotlib.axes.Axes, optional\n        The axes to plot on. If not provided, the current axes will be used.\n    **lc_kwargs\n        Any additional arguments to pass to matplotlib.collections.LineCollection\n        constructor. This should not include the array keyword argument because\n        that is set to the color argument. If provided, it will be overridden.\n\n    Returns\n    -------\n    matplotlib.collections.LineCollection\n        The generated line collection representing the colored line.\n    \"\"\"\n    if \"array\" in lc_kwargs:\n        warnings.warn(\n            'The provided \"array\" keyword argument will be overridden',\n            UserWarning,\n            stacklevel=2,\n        )\n\n    xy = np.stack((x, y), axis=-1)\n    xy_mid = np.concat(\n        (xy[0, :][None, :], (xy[:-1, :] + xy[1:, :]) / 2, xy[-1, :][None, :]), axis=0\n    )\n    segments = np.stack((xy_mid[:-1, :], xy, xy_mid[1:, :]), axis=-2)\n    # Note that\n    # segments[0, :, :] is [xy[0, :], xy[0, :], (xy[0, :] + xy[1, :]) / 2]\n    # segments[i, :, :] is [(xy[i - 1, :] + xy[i, :]) / 2, xy[i, :],\n    #     (xy[i, :] + xy[i + 1, :]) / 2] if i not in {0, len(x) - 1}\n    # segments[-1, :, :] is [(xy[-2, :] + xy[-1, :]) / 2, xy[-1, :], xy[-1, :]]\n\n    lc_kwargs[\"array\"] = c\n    lc = LineCollection(segments, **lc_kwargs)\n\n    # Plot the line collection to the axes\n    ax = ax or plt.gca()\n    ax.add_collection(lc)\n\n    return lc\n\n\n# -------------- Create and show plot --------------\n# Some arbitrary function that gives x, y, and color values\nt = np.linspace(-7.4, -0.5, 200)\nx = 0.9 * np.sin(t)\ny = 0.9 * np.cos(1.6 * t)\ncolor = np.linspace(0, 2, t.size)\n\n# Create a figure and plot the line on it\nfig1, ax1 = plt.subplots()\nlines = colored_line(x, y, color, ax1, linewidth=10, cmap=\"plasma\")\nfig1.colorbar(lines)  # add a color legend\n\nax1.set_title(\"Color at each point\")\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This method is designed to give a smooth impression when distances and color\ndifferences between adjacent points are not too large. The following example\ndoes not meet this criteria and by that serves to illustrate the segmentation\nand coloring mechanism.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "x = [0, 1, 2, 3, 4]\ny = [0, 1, 2, 1, 1]\nc = [1, 2, 3, 4, 5]\nfig, ax = plt.subplots()\nax.scatter(x, y, c=c, cmap='rainbow')\ncolored_line(x, y, c=c, ax=ax, cmap='rainbow')\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Color values between points\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def colored_line_between_pts(x, y, c, ax, **lc_kwargs):\n    \"\"\"\n    Plot a line with a color specified between (x, y) points by a third value.\n\n    It does this by creating a collection of line segments between each pair of\n    neighboring points. The color of each segment is determined by the\n    made up of two straight lines each connecting the current (x, y) point to the\n    midpoints of the lines connecting the current point with its two neighbors.\n    This creates a smooth line with no gaps between the line segments.\n\n    Parameters\n    ----------\n    x, y : array-like\n        The horizontal and vertical coordinates of the data points.\n    c : array-like\n        The color values, which should have a size one less than that of x and y.\n    ax : Axes\n        Axis object on which to plot the colored line.\n    **lc_kwargs\n        Any additional arguments to pass to matplotlib.collections.LineCollection\n        constructor. This should not include the array keyword argument because\n        that is set to the color argument. If provided, it will be overridden.\n\n    Returns\n    -------\n    matplotlib.collections.LineCollection\n        The generated line collection representing the colored line.\n    \"\"\"\n    if \"array\" in lc_kwargs:\n        warnings.warn('The provided \"array\" keyword argument will be overridden')\n\n    # Check color array size (LineCollection still works, but values are unused)\n    if len(c) != len(x) - 1:\n        warnings.warn(\n            \"The c argument should have a length one less than the length of x and y. \"\n            \"If it has the same length, use the colored_line function instead.\"\n        )\n\n    # Create a set of line segments so that we can color them individually\n    # This creates the points as an N x 1 x 2 array so that we can stack points\n    # together easily to get the segments. The segments array for line collection\n    # needs to be (numlines) x (points per line) x 2 (for x and y)\n    points = np.array([x, y]).T.reshape(-1, 1, 2)\n    segments = np.concatenate([points[:-1], points[1:]], axis=1)\n    lc = LineCollection(segments, **lc_kwargs)\n\n    # Set the values used for colormapping\n    lc.set_array(c)\n\n    return ax.add_collection(lc)\n\n\n# -------------- Create and show plot --------------\nx = np.linspace(0, 3 * np.pi, 500)\ny = np.sin(x)\ndydx = np.cos(0.5 * (x[:-1] + x[1:]))  # first derivative\n\nfig2, ax2 = plt.subplots()\nline = colored_line_between_pts(x, y, dydx, ax2, linewidth=2, cmap=\"viridis\")\nfig2.colorbar(line, ax=ax2, label=\"dy/dx\")\n\nax2.set_xlim(x.min(), x.max())\nax2.set_ylim(-1.1, 1.1)\nax2.set_title(\"Color between points\")\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        ".. tags::\n\n   styling: color\n   styling: linestyle\n   plot-type: line\n   level: intermediate\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}