Flexitext advanced usage

logo of a chart:TableBig

Flexitext is a Python library for formatting annotations in matplotlib charts. It allows you to describe which part of a Python string should have specific properties, enabling different styles within the same annotation.

In this post, we'll cover the usage of having a dynamic property applying to a string. For an introduction to flexitext, check this post.

Libraries

First, you need to install flexitext with the following command: pip install flexitext.

Flexitext is one of 2 python libraries that make text formatting for matplotlib easy, along with highlight_text. It was created by Tomás Capretto and is inspired by the R package ggtext.

We'll also need to load matplotlib to create the figure.

import matplotlib.pyplot as plt
from flexitext import flexitext

Dynamically size

There is no built-in method in flexitext to dynamically increase the size of the text, but we can build it ourselved!

The dynamic_text_prop() func:

  • takes a string and applies a property (like size or opacity) to each letter.
  • the property's value starts at initial_value and increases by increment for each letter.
  • it skips spaces, keeping them as-is.
  • it can optionally add an extra property to each letter thanks to the prop_to_add argument
def dynamic_text_prop(string, prop_name, initial_value, increment, prop_to_add=None):
    text = ""
    value = initial_value
    for letter in string:
        if letter != " ":
            if prop_to_add is not None:
                text += f"<{prop_name}:{value}, {prop_to_add}>{letter}</>"
            else:
                text += f"<{prop_name}:{value}>{letter}</>"
            value += increment
        else:
            text += " "
    return text

-

Let's see how to use it in practice:

# Init a figure
fig, ax = plt.subplots(figsize=(8, 8), dpi=200)

text = "this text has a weird size!"
text = dynamic_text_prop(text, prop_name='size', initial_value=10, increment=2)
flexitext(x=0.05, y=0.6, s=text)

# Display the output
plt.show()

Dynamic opacity

And we can imagine exactly the same thing for dynamically changing opacity:

# Init a figure
fig, ax = plt.subplots(figsize=(8, 8), dpi=200)

text = "this text has a weird opacity!"
text = dynamic_text_prop(text, prop_name='alpha',
                         initial_value=0.1, increment=0.03, prop_to_add='size:25')
flexitext(x=0.05, y=0.6, s=text)

# Display the output
plt.show()

Going further

You might be interested in:

Contact & Edit


👋 This document is a work by Yan Holtz. You can contribute on github, send me a feedback on twitter or subscribe to the newsletter to know when new examples are published! 🔥

This page is just a jupyter notebook, you can edit it here. Please help me making this website better 🙏!