-
-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Description
Problem
Creating multi-colored or multi-styled text in Matplotlib requires manual positioning of each text segment with complex spacing calculations.
Users currently need to calculate x-positions manually for each colored segment, which is tedious and error-prone, especially when text properties change.
Proposed solution
Add a richtext() function (or ax.richtext() method) that handles multi-color/multi-style text automatically:
Current approach (manual and tedious):
fig, ax = plt.subplots()
ax.text(0.1, 0.5, "Hello", color='red', fontsize=20)
ax.text(0.35, 0.5, " ", fontsize=20) # Manual spacing calculation!
ax.text(0.4, 0.5, "World", color='blue', fontsize=20) # More manual work!Proposed approach (simple and automatic):
fig, ax = plt.subplots()
ax.richtext(0.5, 0.5,
strings=["Hello", " ", "World"],
colors=["red", None, "blue"],
fontsize=20, ha='center', va='center')Key Features:
- Accepts lists of text segments with corresponding colors/styles
- Automatically calculates spacing and positioning
- Supports word wrapping with
box_widthparameter - Flexible property specification (single values, lists, or dicts)
- Compatible with all standard matplotlib text parameters
Example Use Cases:
- Data visualization: Highlight specific values in different colors
- Scientific plots: Format chemical formulas, mathematical notation
- Publication-quality figures: Mixed text styling in titles/labels
Implementation:
I've created a working proof-of-concept package: mpl-richtext (also on PyPI)
The implementation:
- Uses matplotlib's renderer for accurate text measurements
- Creates positioned Text objects automatically
- ~400 lines of code
- Handles alignment, wrapping, and various text properties
Example output:
Questions for maintainers:
- Is this functionality suitable for matplotlib core?
- Should it be a standalone function, an Axes method, or a custom Artist?
- Any concerns about the implementation approach?
I'm willing to contribute this to matplotlib and adapt it based on maintainer feedback. Open to API redesign or implementation changes as needed.
