Type hint for a matplotlib color?

Question:

I’m type-hinting functions in Python, and not sure what type a matplotlib color should be. I have a function like this:

def plot_my_thing(data: np.ndarray, color: ???):
    # function def here

What should the type be in ???, when it is meant to be a matplotlib color that you can feed into plt.plot() for the type hint? Right now I’m planning to just use Any.

I’ve searched and not found an answer. There are some discussions at GitHub about it:

https://github.com/matplotlib/matplotlib/issues/21505

But that seems like a package-specific problem, though I may not be understanding it.

Asked By: eric

||

Answers:

IMHO, I think the correct answer is: there is no type for matplotlib.colors. It’s a module, and from the documentation, it’s:

A module for converting numbers or color arguments to RGB or RGBA.

So regardless of what you set as a type-hint, it has to do the conversion. There is no benefit specifying str or matplotlib.colors, if you do not supply correct format, it throws an error from colors.py module anyway.

Your origianal choice Any is cleaner than str or matplotlib.colors.

from typing import Any
import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np

def plot_my_thing(colors: Any, fig):
    x = np.linspace(0, 2 * np.pi)
    y = np.sin(x)
    A = 1.0
    for c in colors:
        plt.plot(x, A * y, c=c)
        A *= 0.9
    plt.savefig(fig)


plot_my_thing(["C1", "red", (0.1, 0.2, 0.5), '#0f0f0f80', '#aabbcc',
               '0.8', 'g', 'aquamarine', 'xkcd:sky blue', 'tab:blue'], "mygraph.png")

plot_my_thing(matplotlib.colors.CSS4_COLORS, "mygraph2.png")

output:

mygraph.png
mygraph.png

mygraph2.png
mygraph.png

Answered By: user22390653

Matplotlib introduced type hints in 3.8.0. Now, you can use matplotlib.typing.ColorType which is just an alias for all valid matplotlib colors.

For more information, see the matplotlib typing api reference.

Answered By: khan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.