为matplotlib颜色输入hint?

jrcvhitl  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(175)

我在Python中对函数进行类型提示,但不确定matplotlib颜色应该是什么类型。我有一个这样的函数:

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

如果???中的类型应该是matplotlib颜色,你可以把它输入plt.plot()作为类型提示,那么???中的类型应该是什么呢?现在我打算只使用Any
我搜索了一下,没有找到答案。在GitHub上有一些关于它的讨论:
https://github.com/matplotlib/matplotlib/issues/21505
但这似乎是一个特定于软件包的问题,尽管我可能不理解它。

hmtdttj4

hmtdttj41#

恕我直言,我认为正确的答案是:* matplotlib.colors* 没有类型。它是module,从documentation,它是:
用于将数字或颜色参数转换为 RGBRGBA 的模块。
所以不管你设置什么类型提示,它都必须进行转换。指定strmatplotlib.colors没有任何好处,如果你没有提供正确的格式,它会从colors.py模块抛出错误。
您最初的选择Anystrmatplotlib.colors更干净。

  1. from typing import Any
  2. import matplotlib.colors
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. def plot_my_thing(colors: Any, fig):
  6. x = np.linspace(0, 2 * np.pi)
  7. y = np.sin(x)
  8. A = 1.0
  9. for c in colors:
  10. plt.plot(x, A * y, c=c)
  11. A *= 0.9
  12. plt.savefig(fig)
  13. plot_my_thing(["C1", "red", (0.1, 0.2, 0.5), '#0f0f0f80', '#aabbcc',
  14. '0.8', 'g', 'aquamarine', 'xkcd:sky blue', 'tab:blue'], "mygraph.png")
  15. plot_my_thing(matplotlib.colors.CSS4_COLORS, "mygraph2.png")

产出:
mygraph.png

mygraph2.png

展开查看全部

相关问题