Skip to content

[ENH]: Built-in support for multi-color and multi-style text. #30890

@ra8in

Description

@ra8in

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_width parameter
  • Flexible property specification (single values, lists, or dicts)
  • Compatible with all standard matplotlib text parameters

Example Use Cases:

  1. Data visualization: Highlight specific values in different colors
  2. Scientific plots: Format chemical formulas, mathematical notation
  3. 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:

Example

Questions for maintainers:

  1. Is this functionality suitable for matplotlib core?
  2. Should it be a standalone function, an Axes method, or a custom Artist?
  3. 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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions