{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Legend picking\n\nEnable picking on the legend to toggle the original line on and off\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>This example exercises the interactive capabilities of Matplotlib, and this\n    will not appear in the static documentation. Please run this code on your\n    machine to see the interactivity.\n\n    You can copy and paste individual parts, or download the entire example\n    using the link at the bottom of the page.</p></div>\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nt = np.linspace(0, 1)\ny1 = 2 * np.sin(2 * np.pi * t)\ny2 = 4 * np.sin(2 * np.pi * 2 * t)\n\nfig, ax = plt.subplots()\nax.set_title('Click on legend line to toggle line on/off')\n(line1, ) = ax.plot(t, y1, lw=2, label='1 Hz')\n(line2, ) = ax.plot(t, y2, lw=2, label='2 Hz')\nleg = ax.legend(fancybox=True, shadow=True)\n\nlines = [line1, line2]\nmap_legend_to_ax = {}  # Will map legend lines to original lines.\n\npickradius = 5  # Points (Pt). How close the click needs to be to trigger an event.\n\nfor legend_line, ax_line in zip(leg.get_lines(), lines):\n    legend_line.set_picker(pickradius)  # Enable picking on the legend line.\n    map_legend_to_ax[legend_line] = ax_line\n\n\ndef on_pick(event):\n    # On the pick event, find the original line corresponding to the legend\n    # proxy line, and toggle its visibility.\n    legend_line = event.artist\n\n    # Do nothing if the source of the event is not a legend line.\n    if legend_line not in map_legend_to_ax:\n        return\n\n    ax_line = map_legend_to_ax[legend_line]\n    visible = not ax_line.get_visible()\n    ax_line.set_visible(visible)\n    # Change the alpha on the line in the legend, so we can see what lines\n    # have been toggled.\n    legend_line.set_alpha(1.0 if visible else 0.2)\n    fig.canvas.draw()\n\n\nfig.canvas.mpl_connect('pick_event', on_pick)\n\n# Works even if the legend is draggable. This is independent from picking legend lines.\nleg.set_draggable(True)\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.14.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}