Metadata-Version: 2.5
Name: repelly
Version: 0.5.0
Summary: Repelling, non-overlapping text labels for Plotly figures, solved in the browser.
Project-URL: Homepage, https://github.com/m9o8/repelly
Project-URL: Repository, https://github.com/m9o8/repelly
Project-URL: Issues, https://github.com/m9o8/repelly/issues
Author: Moritz Peist
License-Expression: GPL-3.0-or-later
License-File: LICENSE
License-File: NOTICE
Keywords: annotations,dash,ggrepel,labels,plotly,streamlit,visualization
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Dash
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: JavaScript
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Scientific/Engineering :: Visualization
Requires-Python: >=3.10
Requires-Dist: narwhals>=1.15.1
Requires-Dist: plotly>=6.2
Provides-Extra: dash
Requires-Dist: dash>=3.0; extra == 'dash'
Provides-Extra: static
Requires-Dist: kaleido>=1.0; extra == 'static'
Provides-Extra: streamlit
Requires-Dist: streamlit>=1.52; extra == 'streamlit'
Description-Content-Type: text/markdown

# repelly

[![PyPI](https://img.shields.io/pypi/v/repelly)](https://pypi.org/project/repelly/)
[![Python versions](https://img.shields.io/pypi/pyversions/repelly)](https://pypi.org/project/repelly/)
[![CI](https://github.com/m9o8/repelly/actions/workflows/ci.yml/badge.svg)](https://github.com/m9o8/repelly/actions/workflows/ci.yml)
[![License: GPL v3+](https://img.shields.io/badge/license-GPL--3.0--or--later-blue)](https://github.com/m9o8/repelly/blob/main/LICENSE)

**Repelling, non-overlapping text labels for Plotly in Python**, in the spirit of R's
[ggrepel](https://ggrepel.slowkow.com/). One call labels your points, keeps the labels
readable as you zoom, and leaves the rest of your chart alone.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/m9o8/repelly/main/docs/images/volcano-dark.png">
  <img alt="Volcano plot with gene labels that avoid each other, the points, the threshold lines and the legend" src="https://raw.githubusercontent.com/m9o8/repelly/main/docs/images/volcano.png">
</picture>

## 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](https://raw.githubusercontent.com/m9o8/repelly/main/docs/images/before-after.png)

- **[Clear of everything](https://github.com/m9o8/repelly#avoiding-lines-and-layout):**
  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](https://github.com/m9o8/repelly#interactive-apps):** labels can carry
  hover text, respond to clicks, and be replaced or removed by name, which suits Dash.
- **[Runs anywhere Plotly does](https://github.com/m9o8/repelly#output):** HTML files,
  notebooks, Dash, Streamlit and static images.

## Installation

```bash
pip install repelly
```

Optional extras add static image export, Dash and Streamlit:

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

Requires Python 3.10+ and Plotly 6.2+.

## Quick start

```python
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.

## Gallery

<table>
  <tr>
    <td><a href="https://raw.githubusercontent.com/m9o8/repelly/main/docs/images/labels-off-lines.png"><img alt="Event labels kept clear of every line of a time series" src="https://raw.githubusercontent.com/m9o8/repelly/main/docs/images/labels-off-lines.png"></a></td>
    <td><a href="https://raw.githubusercontent.com/m9o8/repelly/main/docs/images/line-end-labels.png"><img alt="Labels at the ends of lines, stacked in a gutter" src="https://raw.githubusercontent.com/m9o8/repelly/main/docs/images/line-end-labels.png"></a></td>
    <td><a href="https://raw.githubusercontent.com/m9o8/repelly/main/docs/images/labels-off-layout.png"><img alt="Labels clear of threshold lines, an annotation and the legend" src="https://raw.githubusercontent.com/m9o8/repelly/main/docs/images/labels-off-layout.png"></a></td>
  </tr>
  <tr>
    <td align="center"><a href="https://github.com/m9o8/repelly#avoiding-lines-and-layout">Clear of every line</a></td>
    <td align="center"><a href="https://github.com/m9o8/repelly#labels-at-line-ends">Labels at line ends</a></td>
    <td align="center"><a href="https://github.com/m9o8/repelly#avoiding-lines-and-layout">Clear of your annotations</a></td>
  </tr>
</table>

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](https://narwhals-dev.github.io/narwhals/) supports works, including pandas,
polars and pyarrow:

```python
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.

```python
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:

```python
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:

```python
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:

```python
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`:

```python
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:

```python
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`:

```python
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:

```python
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:

```python
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:

  ```python
  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

<details>
<summary><b>All options</b> of <code>add_text_repel</code> and <code>add_label_repel</code></summary>

| 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`.

</details>

### 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.

<details>
<summary><b>Limitations</b></summary>

- 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.

</details>

## Development

The project uses [pixi](https://pixi.sh). Browser tests need Chrome or Edge installed.

```bash
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](https://github.com/slowkow/ggrepel) by Kamil Slowikowski and contributors,
  the original repelling-label package.
- [plotly.repel](https://github.com/bigomics/plotly.repel) by Santiago Cano Muniz, which
  pioneered browser-side solving for Plotly and the `add_text_repel` interface.

See [NOTICE](https://github.com/m9o8/repelly/blob/main/NOTICE) for full credits.

## License

Copyright (C) 2026 Moritz Peist. Licensed under the
[GNU General Public License, version 3 or later](https://github.com/m9o8/repelly/blob/main/LICENSE).

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.
