Skip to main content

repelly

PyPI Python versions CI License: GPL v3+

Repelling, non-overlapping text labels for Plotly in Python, in the spirit of R's ggrepel. One call labels your points, keeps the labels readable as you zoom, and leaves the rest of your chart alone.

Volcano plot with gene labels that avoid each other, the points, the threshold lines and the legend

Why repelly

Plotly places text labels where you put them, so in a crowded chart they pile up. repelly puts each label right beside its point where there is room, and moves the rest to a free spot nearby with a leader line back to their point:

Plotly's own text labels overlap; repelly's labels do not

  • Clear of everything: labels avoid each other, markers and lines, and your own annotations, threshold lines and legend.
  • Live: labels are placed in the browser and follow zoom, pan, resize and animation.
  • Native: they are ordinary Plotly annotations, so they appear in the modebar's PNG download and in static image export.
  • Fits your workflow: plotly.express, facets, animations, scattergl, data frames from pandas, polars or pyarrow, and every axis type.
  • Interactive: labels can carry hover text, respond to clicks, and be replaced or removed by name, which suits Dash.
  • Runs anywhere Plotly does: HTML files, notebooks, Dash, Streamlit and static images.

Installation

pip install repelly

Optional extras add static image export, Dash and Streamlit:

pip install "repelly[static]"
pip install "repelly[dash]"
pip install "repelly[streamlit]"

Requires Python 3.10+ and Plotly 6.2+.

Quick start

import pandas as pd
import plotly.express as px
from repelly import add_text_repel

df = pd.DataFrame(
    {
        "x": [1, 1.05, 1.02, 0.98, 1.5, 2.0],
        "y": [2, 2.02, 2.05, 1.97, 2.5, 3.0],
        "gene": ["TP53", "EGFR", "MYC", "PTEN", "BRCA1", "KRAS"],
    }
)

fig = px.scatter(df, x="x", y="y")
fig = add_text_repel(fig, "x", "y", "gene", data=df)
fig.show()

add_text_repel returns a copy of your figure with the labels added, so keep the returned value. The labels live in the figure's layout.meta, so they survive copies, go.Figure(fig) and JSON round trips.

Event labels kept clear of every line of a time series Labels at the ends of lines, stacked in a gutter Labels clear of threshold lines, an annotation and the legend
Clear of every line Labels at line ends Clear of your annotations

The full gallery, with interactive versions of these and more, is built by python examples/gallery.py.

Basics

Data frames

Pass data to use column names, as in plotly.express. Any data frame that narwhals supports works, including pandas, polars and pyarrow:

fig = add_text_repel(fig, "x", "y", "gene", data=df, priority="score")

Every parameter that takes one value per label accepts a column name. For direction and color, a string that is one of their own values stays a value: direction="x" is a direction, and color="red" reads a column named red only if data has one. Series and arrays from pandas, polars and pyarrow also work without data.

Labelling existing traces

Omit x and y to label the points of scatter traces already in the figure. This is the simplest route for facets and animations. Labels hide when their trace is hidden from the legend, and each animation frame gets its own labels.

fig = px.scatter(df, x="gdpPercap", y="lifeExp", facet_col="continent", text="country")
fig.update_traces(mode="markers")  # repelly draws the text
fig = add_text_repel(fig)

fig = px.scatter(df, x="x", y="y", custom_data=["name"])
fig = add_text_repel(fig, text=lambda trace: trace.customdata[:, 0])

text defaults to each trace's text, then hovertext. Narrow the traces with selector, row and col.

Boxed labels

add_label_repel takes the same arguments and draws each label on a filled box:

from repelly import add_label_repel

fig = add_label_repel(fig, "x", "y", "gene", data=df, label={"bgcolor": "lightyellow"})

Placement

Where a point has room, its label sits right beside it, trying east, north, west and south, then the diagonals, in order of priority. Labels in a crowd, and those with no room beside their point, are repelled to a free spot nearby with a leader line; once every label has its place, any that now has room beside its point moves there. This keeps sparse areas tidy and makes them quick to solve. Pass prefer_sides=False to repel every label instead, for the free-form look of ggrepel.

Avoiding lines and layout

Labels keep clear of more than each other:

  • Markers of every scatter trace in the subplot, labelled or not (avoid_points).
  • Lines of line traces, including the line through a label's own point (avoid_lines). A label with no room left covers a line rather than another label.
  • Your layout: annotations and their arrows, shape outlines such as threshold lines from add_hline and add_vline, and a legend inside the plot (avoid_layout). Filled shapes without an outline, such as bands from add_vrect, are backdrops that labels may cover.

All three are on by default and apply to each call's own labels, so one call can avoid lines while another ignores them:

fig.add_hline(y=1.3, line_dash="dot")
fig = add_text_repel(fig, "x", "y", "gene", data=df, avoid_lines=False)

Labels at line ends

Label only the last point of each line: points with an empty label get none. Labels stay inside the plot area, so first make room right of the data. xlim keeps the labels in that gutter, nudge_x sets the gap in pixels, direction="y" lets labels move only up and down so they stack, and color="trace" matches each line:

fig = px.line(df, x="date", y="value", color="ticker")
last = df["date"].max()
fig.update_xaxes(range=[df["date"].min(), last + pd.Timedelta(days=120)])
fig = add_text_repel(
    fig,
    text=lambda trace: [""] * (len(trace.x) - 1) + [trace.name],
    direction="y",
    nudge_x=30,
    xlim=(last, None),
    color="trace",
    max_overlaps=None,
)

Subplots

For explicit coordinates, choose the subplot with row and col, or xref and yref:

fig = add_text_repel(fig, x, y, names, row=1, col=2)

Interactive apps

Updating and removing labels

Give a set of labels a name to replace it later: adding labels under a name already in the figure replaces them in place. remove_repel takes them out again, all or by name. Both accept a figure dict, so a Dash callback can work on the graph's current figure:

from repelly import remove_repel


@app.callback(
    Output("graph", "figure"), Input("genes", "value"), State("graph", "figure")
)
def update(genes, figure):
    if not genes:
        return remove_repel(figure, "genes")
    rows = df[df.gene.isin(genes)]
    return add_text_repel(figure, rows.x, rows.y, rows.gene, name="genes")

Hover and click

hovertext shows text when the pointer is over a label, styled by hoverlabel. clickable=True makes labels respond to clicks, which Plotly reports as a plotly_clickannotation event and Dash as the graph's clickAnnotationData. clicked_label turns that into the label, with the matching entry of ids:

from repelly import clicked_label

fig = add_text_repel(
    fig,
    "x",
    "y",
    "gene",
    data=df,
    hovertext="description",
    ids="gene_id",
    clickable=True,
    name="genes",
)


@app.callback(
    Output("details", "children"),
    Input("graph", "clickAnnotationData"),
    State("graph", "figure"),
)
def show_details(click, figure):
    label = clicked_label(figure, click)
    return None if label is None else describe(label.id)

ClickedLabel also gives the label's text, its point's x and y, and point, the point's row among the values given or its point number in the trace.

Dash

Call init_app once. Figures then work as normal, including as callback outputs:

from dash import Dash, dcc
import repelly.dash

app = Dash(__name__)
repelly.dash.init_app(app)
app.layout = dcc.Graph(figure=fig)

Placing labels for the first time, or changing which labels are shown, updates the graph's layout, so a callback listening to relayoutData also fires then. When a re-solve only moves labels, repelly moves them in place without a relayout, so that callback does not fire.

Streamlit

st.plotly_chart sends only the figure, not the script that places the labels, so init adds that script to the page. Call it in each run of the script, then use st.plotly_chart as normal:

import streamlit as st
import repelly.streamlit

repelly.streamlit.init()
st.plotly_chart(fig)

Labels re-solve on zoom, resize and reruns, and work with on_select, tabs and multipage apps. init needs Streamlit 1.52 or newer. It runs repelly's script in the page through st.html(..., unsafe_allow_javascript=True).

Output

Notebooks

JupyterLab uses its built-in Plotly, so charts work offline and add little to the notebook. When you reopen a saved notebook, JupyterLab shows a saved preview without labels until you hover over the chart.

VS Code needs internet access for notebook charts. It does not let scripts reach its built-in Plotly, so repelly shows each chart in an iframe that loads Plotly from a CDN. Offline, the chart shows a message instead. To work offline anyway, call fig.show(include_plotlyjs=True), which embeds about 5 MB in each output. HTML files, browser output, Dash and static images all work offline in VS Code as usual.

Static images

fig.write_image(...) and fig.to_image(...) solve the labels in headless Chrome, using Kaleido's browser or any installed Chrome, Chromium or Edge (set BROWSER_PATH to choose one). Positions are computed for the export size.

repelly.bake(fig, width=..., height=...) returns a plain figure with the positions fixed, if you need one to pass elsewhere.

Plain figures and plotly.io

The returned figure is a RepelFigure, a go.Figure whose show, to_html, write_html, to_image and write_image methods include the labels. You can also use plain figures and plotly.io:

  • Display works for any figure. Importing repelly teaches Plotly's renderers to draw the labels, so pio.show(fig), go.Figure(fig).show() and notebook display all work. Figures without labels are rendered exactly as before.

  • For HTML and image export of a plain figure, use repelly's functions. They take the same arguments as their plotly.io counterparts and accept any figure or figure dict:

    import repelly
    
    repelly.write_html(fig, "plot.html")
    repelly.write_image(fig, "plot.png", width=800, height=500)
    # also repelly.to_html, repelly.to_image and repelly.show
    
  • To make Plotly's own export include labels, for example when another library calls fig.write_html for you, opt in once with repelly.patch_plotly(). After that, plotly.io.to_html, write_html, to_image and write_image, and the figure methods of the same names, include the labels. repelly.patch_plotly(False) undoes it.

Reference

All options of add_text_repel and add_label_repel
Argument Default Purpose
data none Data frame whose column names the per-label parameters may then use
name none Name of this set of labels; adding under the same name replaces it
row, col, secondary_y, xref, yref primary axes Target subplot for explicit x and y
selector all traces Which traces to label when x and y are omitted
priority none Higher values survive culling first
visible all Boolean mask; a hidden label's point still keeps others away if it is drawn as a marker
frame none Animation frame name per label, for explicit x and y
force 1.0 Separation strength; each overlapping pair uses the average of its two values, limited to 0.05 to 1
force_pull 1.0 Pull back towards the anchor
box_padding, point_padding 2, 2 Gaps in pixels
direction "both" Restrict movement to "x" or "y"; one value or one per label
color font colour Text colour; one value, one per label, or "trace" to match each point when labelling traces
nudge_x, nudge_y 0 Preferred offset from the point in pixels, positive right and up; one value or one per label
xlim, ylim plot area (low, high) data values labels must stay within; None leaves a side open
hovertext, hoverlabel none Text shown when hovering over a label, one per label, and its Plotly hoverlabel style
clickable False Labels respond to clicks, for plotly_clickannotation, Dash's clickAnnotationData and clicked_label
ids none A value per label, such as a row key, that clicked_label returns
max_overlaps 10 Drop a label starting on more than this many higher-priority labels; None keeps all
max_labels none Maximum labels per subplot from this call, by priority
max_iter, max_time_ms 400, 40 Solver limits for one solve; time in milliseconds
initial_max_time_ms 250 Time limit when labels are first placed; the solver stops sooner if it finishes
seed 42 Makes placement reproducible
min_segment_length 6 Hide the connector below this distance in pixels
prefer_sides True Place labels right beside their point where there is room (east, north, west, south, then diagonally) before repelling; False repels every label, as ggrepel does
avoid_points True Keep labels off every marker in the subplot
avoid_lines True Keep labels off the lines of line traces; a label with no room left covers a line rather than another label
avoid_layout True Keep labels off your own annotations, shape outlines such as threshold lines, and a legend inside the plot; filled bands without an outline may be covered
drop_unresolved False Hide labels that still overlap after solving
font, segment Plotly defaults Styling; segment takes color, width, arrowhead, arrowsize
align "center" Line up the lines of a multi-line label: "left", "center" or "right"
on all events Re-solve on any of "render", "zoom", "resize", "frame"; applies to the whole figure, and None keeps what an earlier call set; the first render always solves

add_label_repel also takes label, the box style: any of bgcolor, bordercolor, borderwidth and borderpad.

Diagnostics

Labels that are hidden by max_overlaps, or that still overlap another label or cover a marker, annotation, shape outline or legend after solving, are reported with a warning in the browser console. bake, to_image and write_image raise the same information as a Python warning. Avoiding lines is a preference rather than a rule, so a label left on a line is not reported.

Limitations
  • Only cartesian scatter and scattergl traces can be labelled from traces, and only their markers and lines are avoided; bars, areas under fill and other trace types are not.
  • Avoiding lines reads every point of every line trace on each solve, which takes about 1 ms per 10,000 points on a typical laptop. For series of millions of points, avoid_lines=False keeps zooming quick.
  • FigureWidget is not supported.
  • A custom Plotly renderer registered after importing repelly draws labels from the next call to add_text_repel, add_label_repel or repelly.show.
  • patch_plotly does not reach code that imported a function by name before the call, as in from plotly.io import write_html.
  • Configuration lives in layout.meta, so that must be unset or a dict. Replacing it afterwards removes the labels.
  • Solving freezes autoranged axes at their current range, because annotations would otherwise change the range they were placed in. Double-click still resets the view.

Development

The project uses pixi. Browser tests need Chrome or Edge installed.

pixi install
pixi run hooks      # format and lint before each commit
pixi run lint       # ruff format and ruff check --fix
pixi run test-all   # Python and JavaScript tests
pixi run -e min test-all   # against the oldest supported dependencies
pixi run check-dist # build and validate the package

If the commit hook reformats files, stage them and commit again.

python examples/gallery.py writes the example gallery to gallery_output/, and python examples/gallery.py --readme-images regenerates the images in this README.

To release, update __version__ in src/repelly/__init__.py and the matching VERSION in src/repelly/js/runtime.js, then publish a GitHub release tagged vX.Y.Z.

Acknowledgements

repelly brings the ideas of two R packages to Python:

  • ggrepel by Kamil Slowikowski and contributors, the original repelling-label package.
  • plotly.repel by Santiago Cano Muniz, which pioneered browser-side solving for Plotly and the add_text_repel interface.

See NOTICE for full credits.

License

Copyright (C) 2026 Moritz Peist. Licensed under the GNU General Public License, version 3 or later.

Interactive output embeds repelly's GPL-licensed JavaScript, so HTML files and Dash pages you distribute contain GPL code. The script keeps its license notice for this purpose. Static images and baked figures do not contain it.

Metadata

Release files for repelly 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for repelly 0.5.0
File Size Uploaded Provenance Actions
repelly-0.5.0.tar.gz 117.9 kB With provenance Details for repelly-0.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for repelly 0.5.0
File Interpreter ABI Platform Actions
repelly-0.5.0-py3-none-any.whl Python 3 none any Details for repelly-0.5.0-py3-none-any.whl

Total release size: 196.9 kB

Release files / repelly-0.5.0.tar.gz

Download URL repelly-0.5.0.tar.gz
Size 117.9 kB
Tags Source
SHA-256 checksum
How to use checksums
b46b695208f81b806066f03d04840eed0f1d8d4e1408b224660639f9956c0f52
BLAKE2b-256 checksum
How to use checksums
ad8f699e831f6ba7a8919e12f1d9cbe635c81a141023b420550826887b0047e8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / repelly-0.5.0-py3-none-any.whl

Download URL repelly-0.5.0-py3-none-any.whl
Size 79.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9361d60863b6d37e579aa74c28c19ebebb9b79cb1558e4154b53ee8eaffe826d
BLAKE2b-256 checksum
How to use checksums
0a4084fd01dd9ef62c5230896a8575631577c4710724e5e7f098ec9f117abd08
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Security for repelly 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for repelly-0.5.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page