{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Zoom-level dependent labels\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If there are many data points, their labels may be difficult to read. To selectively display\nlabels depending on the zoom level, use the :class:`plotly.graph_objects.FigureWidget` class and\nregister a callback.\n\n.. hint::\n\n You will need to install the |anywidget| package to use\n the :class:`plotly.graph_objects.FigureWidget` class. See\n the [Plotly documentation](https://plotly.com/python/figurewidget)_ for details.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import functools\n\nimport plotly\nimport plotly.graph_objects as go\nimport scipy\n\nfrom pdendro import attach_dendrogram\n\nX = plotly.data.iris()[[\"sepal_length\", \"sepal_width\", \"petal_length\", \"petal_width\"]]\nZ = scipy.cluster.hierarchy.linkage(X)\n\nfig = go.FigureWidget()\n_ = attach_dendrogram(fig, Z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following code registers a callback to change labels on zooming:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def update_ticks(axis, axis_range, all_ticktext, max_n_ticks):\n \"\"\"Update ticks for limiting the number.\"\"\"\n step = int(abs(axis_range[1]-axis_range[0])//max_n_ticks) + 1\n axis.update(tickvals=list(range(0, len(all_ticktext), step)), ticktext=all_ticktext[::step])\n\n# axis for data point labels\naxis = fig.layout.xaxis\n\n# get all labels\nall_ticks = zip(axis.tickvals, axis.ticktext, strict=True)\nall_ticks = sorted(all_ticks, key=lambda item: item[0])\n_, all_ticktext = zip(*all_ticks, strict=True)\n\n# register a callback\ncallback = functools.partial(update_ticks, all_ticktext=all_ticktext, max_n_ticks=5)\naxis.on_change(callback, \"range\")\n\n# initialize\ncallback(axis, axis.range)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The figure can be shown as follows:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
The figure is not displayed in the documentation because\n the :class:`plotly.graph_objects.FigureWidget` object can only be displayed in |jupyter|.\n The following images illustrate the appearance at various zoom levels:\n\n .. image:: /_galleries/examples/data_point_label/zoomed_out_figure.svg\n :alt: zoomed-out figure\n :align: center\n\n .. image :: /_galleries/examples/data_point_label/zoomed_in_figure.svg\n :alt: zoomed-in figure\n :align: center