Matplotlib plt.xlabel() 与 ax.set_xlabel()

inf*_*nge 3 python oop matplotlib

我正在使用一些在 Python 中使用 matplotlib 单例版本的代码,即它有类似的调用

plt.figure()
...
plt.xlabel("abc")
Run Code Online (Sandbox Code Playgroud)

我正在尝试将其转换为功能/无内存版本:

fig,ax = plt.subplots()
...
ax.set_xlabel("abc")
Run Code Online (Sandbox Code Playgroud)

有几个问题:

  • 是否有直接设置轴的 xlabel 的选项?就像是ax.xlabel = "xlabel string"

  • 从文档来看,这似乎是不可能的。(甚至我们不能设置私有属性)

  • 还是总是需要经过setter?这一直让我感到困惑,并且让我觉得它不是Pythonic。

  • 为什么 API 从plt.xlabel()变为ax.set_xlabel()

use*_*663 5

Matplotlib 具有 pyplot 接口,后来开发了面向对象的接口,如文档中所述(https://matplotlib.org/3.2.1/tutorials/introductory/lifecycle.html)。

现在首选后者,因此使用Fig, ax = plt.subplots,然后在ax上使用setter方法。