简体   繁体   English

来自 plt.subplots() 的 matplotlib 轴的精确类型注释数组(numpy.ndarray)

[英]Precise type annotating array (numpy.ndarray) of matplotlib Axes from plt.subplots()

I wanted to have no errors while using VSCode Pylance type checker.我希望在使用 VSCode Pylance 类型检查器时没有错误。

How to type the axs correctly in the following code:如何在以下代码中正确键入axs

import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2)

In the image below, you can see that Pylance on VSCode is detecting an error.在下图中,您可以看到 VSCode 上的 Pylance 检测到错误。

在此处输入图像描述

It turns out that strongly typing the axs variable is not straightforward at all and requires to understant well how to type np.ndarray .事实证明,强输入axs变量一点也不简单,需要很好地理解如何输入np.ndarray

See this question and this question for more details.有关更多详细信息,请参阅此问题此问题

The simplest and most powerful solution is to wrap numpy.ndarray with ' characters, in order to avoid the infamous TypeError: 'numpy._DTypeMeta' object is not subscriptable when Python tries to interpret the [] in the expression.最简单和最强大的解决方案是用'字符包装numpy.ndarray ,以避免臭名昭著的 TypeError:当 Python 尝试解释表达式中的 [] 时,'numpy._DTypeMeta' object is not subscriptable。

An example:一个例子:

import matplotlib.pyplot as plt
import numpy as np
import numpy.typing as npt
import seaborn as sns
from typing import cast, Type, Sequence
import typing 

sns.set() 

# Some example data to display
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, axs = plt.subplots(
    2, 2, 
    figsize=(12, 10) # set graph size
)

# typechecking operation
NDArrayOfAxes: typing.TypeAlias = 'np.ndarray[Sequence[Sequence[plt.Axes]], np.dtype[np.object_]]'
axs = cast(np.ndarray, axs)

axs[0, 0].plot(x, y)
axs[0, 0].set_title("main")
axs[1, 0].plot(x, y**2)
axs[1, 0].set_title("shares x with main")
axs[1, 0].sharex(axs[0, 0])
axs[0, 1].plot(x + 1, y + 1)
axs[0, 1].set_title("unrelated")
axs[1, 1].plot(x + 2, y + 2)
axs[1, 1].set_title("also unrelated")
fig.tight_layout()

Which is well detected by Pylance and runs correctly: Pylance 可以很好地检测到并正确运行:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 plt.subplots() 中的轴是“numpy.ndarray”对象,没有属性“plot” - Axes from plt.subplots() is a “numpy.ndarray” object and has no attribute “plot” Numpy.ndarray:按数组的特定轴进行迭代 - Numpy.ndarray: iteration by specific axes of an array Matplotlib:在plt.subplots中绘制多个直方图 - Matplotlib: Plotting multiple histograms in plt.subplots TypeError:不可散列的类型:plt.scatter中的'numpy.ndarray' - TypeError: unhashable type: 'numpy.ndarray' in plt.scatter 设置matplotlib中用plt.subplots创建的图形的高度和宽度? - Set height and width of figure created with plt.subplots in matplotlib? 如何使用 ipywidget 的 `interact` 和 matplotlib 的 `plt.subplots()`? - How to use ipywidget's `interact` with matplotlib's `plt.subplots()`? 在 matplotlib 中注释子图将图形缩放到最大轴 - Annotating subplots in matplotlib scales the figure to the largest axes matplotlib scatter:TypeError:unhashable type:'numpy.ndarray' - matplotlib scatter: TypeError: unhashable type: 'numpy.ndarray' 将numpy数组转换为列表将返回numpy.ndarray类型 - Converting numpy array to list returns type numpy.ndarray 将一个numpy数组映射到一个double(不可散列的类型:'numpy.ndarray') - map a numpy array to a double (unhashable type: 'numpy.ndarray')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM