{
"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, **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 : 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 # Default the capstyle to butt so that the line segments smoothly line up\n default_kwargs = {\"capstyle\": \"butt\"}\n default_kwargs.update(lc_kwargs)\n\n # Compute the midpoints of the line segments. Include the first and last points\n # twice so we don't need any special syntax later to handle them.\n x = np.asarray(x)\n y = np.asarray(y)\n x_midpts = np.hstack((x[0], 0.5 * (x[1:] + x[:-1]), x[-1]))\n y_midpts = np.hstack((y[0], 0.5 * (y[1:] + y[:-1]), y[-1]))\n\n # Determine the start, middle, and end coordinate pair of each line segment.\n # Use the reshape to add an extra dimension so each pair of points is in its\n # own list. Then concatenate them to create:\n # [\n # [(x1_start, y1_start), (x1_mid, y1_mid), (x1_end, y1_end)],\n # [(x2_start, y2_start), (x2_mid, y2_mid), (x2_end, y2_end)],\n # ...\n # ]\n coord_start = np.column_stack((x_midpts[:-1], y_midpts[:-1]))[:, np.newaxis, :]\n coord_mid = np.column_stack((x, y))[:, np.newaxis, :]\n coord_end = np.column_stack((x_midpts[1:], y_midpts[1:]))[:, np.newaxis, :]\n segments = np.concatenate((coord_start, coord_mid, coord_end), axis=1)\n\n lc = LineCollection(segments, **default_kwargs)\n lc.set_array(c) # set the colors of each segment\n\n return ax.add_collection(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\n# Set the axis limits and tick positions\nax1.set_xlim(-1, 1)\nax1.set_ylim(-1, 1)\nax1.set_xticks((-1, 0, 1))\nax1.set_yticks((-1, 0, 1))\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()"
]
}
],
"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.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}