tomicapretto / flexitext

Flexitext: Draw styled text in Matplotlib
https://tomicapretto.github.io/flexitext/
MIT License
113 stars 7 forks source link

feature suggestion: dynamic props #14

Open JosephBARBIERDARNAL opened 1 month ago

JosephBARBIERDARNAL commented 1 month ago

Hi Tomi ! I've come from the Python graph gallery that you probably know (: I'm in the process of adding some flexitext examples to the gallery. And while testing things out, I came up with the idea of making it simpler to create this type of annotation (see below). I quickly created a simple function to illustrate it.

Is this something you'd be interested in adding to your library? If so, I'm ready to do the PR and discuss how to implement it in practice so that it's robust and still compatible with other flexitext features.

import matplotlib.pyplot as plt
from flexitext import flexitext

def dynamic_text_prop(string, prop_name, initial_value, increment=2, 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

# 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)
flexitext(x=0.05, y=0.6, s=text)

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:20')
flexitext(x=0.05, y=0.3, s=text)

# Display the output
plt.show()
Screenshot 2024-07-16 at 11 18 19

Note: this would also be interesting with colours, which would be highly compatible with pypalettes, a library I created to facilitate access to colour maps in python.

tomicapretto commented 1 month ago

This is fantastic! I would love to have it. Feel free to open a PR. I'll review it and if possible i'll try to contribute with ideas. Thanks!

JosephBARBIERDARNAL commented 1 month ago

cool! I'll try to open a draft soon