Phlya / adjustText

A small library for automatically adjustment of text position in matplotlib plots to minimize overlaps.
https://adjusttext.readthedocs.io/
MIT License
1.49k stars 87 forks source link

Example of integrating seaborn.object() #162

Open TKMarkCheng opened 10 months ago

TKMarkCheng commented 10 months ago

There currently is no guide to integrating adjustText into seaborn, a popular matplotlib wrapper.

This is especially detrimental to seaborn.objects() which aims to have the same grammar as ggplot2, but does not have easy options to space out text like ggrepel.

After testing, I have demonstrated that adjustText can be integrated into seaborn.objects() using principles demonstrated from #58 and using seaborn.objects.Plot.on

Generic solution:

# your plot (with subfigures, can be declared by .facet())
p=so.Plot().add(so.Text())
f=plt.figure(figsize=(24, 10), dpi=200, layout="constrained")
p.on(f).plot()
# In my instance I was using subplots
for ax in f.axes:
    adjust_text(texts=[child for child in ax.get_children() if isinstance(child,mpl.text.Text)][:-3],ax=ax,arrowprops=dict(arrowstyle='-', color='gray', alpha=.65))
#[:-3] because last three Text objects are x-axis, y-axis, and title respectively.

Lastly, regarding the questions about time discrepancy between subplots raised in #58, initially setting a random arbitrary Text location helps speed up the process on my instance.

so.Text(valign='top')

I will push a full example .ipynb once I finish my paper...