Text and Annotations
Contents
Text and Annotations#
Note
Support for modifying text is not complete as none of the function implemented support updating fontdict
or other text properties like size and color. However, the core functionality is there to place text, change it’s position, or change what it reads. see https://github.com/ianhi/mpl-interactions/issues/247 for updates.
%matplotlib ipympl
import matplotlib.pyplot as plt
import numpy as np
from mpl_interactions import ipyplot as iplt
Working with text strings.#
There are two ways to dynamically update text strings in mpl-interactions.
Use a function to return a string
Use a named string formatting
You can also combine these and have your function return a string that then gets formatted.
In the example below the xlabel
is generated using a function and the title
is generated using the formatting approach.
fig, ax = plt.subplots()
x = np.linspace(0, np.pi, 100)
def y(x, volts, tau):
return np.sin(x * tau) * volts
ctrls = iplt.plot(x, y, volts=(0.5, 10), tau=(1, 10, 100))
def xlabel_func(tau):
# you can do arbitrary python here to make a more
# complicated string
return f"Time with a max tau of {np.round(tau, 3)}"
with ctrls["tau"]:
iplt.xlabel(xlabel_func)
with ctrls:
# directly using string formatting
# the formatting is performed in the update
iplt.title(title="The voltage is {volts:.2f}")
Arbitrarily placed text#
For this you can use interactive_text()
. Currently plt.annotation
is not supported.
fig, ax = plt.subplots()
theta = np.linspace(0, 2 * np.pi, 100)
def gen_string(theta):
return f"angle = {np.round(np.rad2deg(theta))}"
def fx(theta):
return np.cos(theta)
def fy(x, theta):
return np.sin(theta)
ctrls = iplt.text(fx, fy, gen_string, theta=theta)
ax.set_xlim([-1.25, 1.25])
_ = ax.set_ylim([-1.25, 1.25])
Since the x
and y
positions are scalars you can also do nifty things like directly define them by a slider shorthand in the function.
fig, ax = plt.subplots()
ctrls = iplt.text((0, 1, 100), (0.25, 1, 100), "{x:.2f}, {y:.2f}")