{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# pyplot with GTK3\n\nAn example of how to use pyplot to manage your figure windows, but modify the\nGUI by accessing the underlying GTK widgets.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib\n\nmatplotlib.use('GTK3Agg') # or 'GTK3Cairo'\nimport gi\n\nimport matplotlib.pyplot as plt\n\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\n\nfig, ax = plt.subplots()\nax.plot([1, 2, 3], 'ro-', label='easy as 1 2 3')\nax.plot([1, 4, 9], 'gs--', label='easy as 1 2 3 squared')\nax.legend()\n\nmanager = fig.canvas.manager\n# you can access the window or vbox attributes this way\ntoolbar = manager.toolbar\nvbox = manager.vbox\n\n# now let's add a button to the toolbar\nbutton = Gtk.Button(label='Click me')\nbutton.show()\nbutton.connect('clicked', lambda button: print('hi mom'))\n\ntoolitem = Gtk.ToolItem()\ntoolitem.show()\ntoolitem.set_tooltip_text('Click me for fun and profit')\ntoolitem.add(button)\n\npos = 8 # where to insert this in the toolbar\ntoolbar.insert(toolitem, pos)\n\n# now let's add a widget to the vbox\nlabel = Gtk.Label()\nlabel.set_markup('Drag mouse over axes for position')\nlabel.show()\nvbox.pack_start(label, False, False, 0)\nvbox.reorder_child(toolbar, -1)\n\n\ndef update(event):\n if event.xdata is None:\n label.set_markup('Drag mouse over axes for position')\n else:\n label.set_markup(\n f'x,y=({event.xdata}, {event.ydata})')\n\n\nfig.canvas.mpl_connect('motion_notify_event', update)\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.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }