键入 matplotlib 颜色的提示?

问题描述 投票:0回答:1

我在 Python 中使用类型提示函数,不确定 matplotlib 颜色应该是什么类型。我有一个这样的功能:

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

当它是一个可以输入到

???
中作为类型提示的 matplotlib 颜色时,
plt.plot()
中的类型应该是什么?现在我打算只使用
Any

我已经搜索过但没有找到答案。 GitHub 上有一些关于它的讨论:

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

但这似乎是一个特定于包的问题,尽管我可能不理解它。

python matplotlib type-hinting
1个回答
0
投票

恕我直言,我认为正确的答案是:没有

matplotlib.colors
的类型。这是一个
module
,从文档来看,它是:

用于将数字或颜色参数转换为RGBRGBA的模块。

因此,无论您设置什么类型提示,它都必须进行转换。指定

str
matplotlib.colors
没有任何好处,如果您不提供正确的格式,它无论如何都会从
colors.py
模块抛出错误。

您最初的选择

Any
str
matplotlivb.colors
更干净。

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

def plot_my_thing(colors: Any):
    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("mygraph.png")


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

输出:

© www.soinside.com 2019 - 2024. All rights reserved.