python - 创建一个类来生成子图

标签 python matplotlib

我想知道如何设计一个好的类来生成适合我目的的 matplotlib 图。 我想要获得的第一件事是一个可以按如下方式调用的类,
但我不知道如何设计这样的类(class)。

这就是我想使用它的方式:

fig,axs = MyClass(parameter...) 

如何正确使用它?

编辑 非常感谢@ImportanceOfBeingErnest,你给了我一个很好的起点,我现在的问题是,既然你告诉我如何将**参数传递给类(class),你怎么看例如,如何传递变量列表以便在 ax1,ax2,ax3,ax4 中绘制?再次感谢您的帮助总是非常宝贵

最佳答案

基本上,您不能,或者至少不应该。一个类的返回应该是它自己的一个实例。

但是你可以调用一个类,例如

import matplotlib.pyplot as plt

class MyClass():
    def __init__(self, **parameters):
        self.fig, self.axs = plt.subplots(**parameters)

    def __call__(self):
        return self.fig, self.axs

fig, axs = MyClass(figsize=(6,5))()

这样做的缺点是您直接失去了创建的类实例的任何处理程序。这意味着将上面的代码写成函数会简单得多,

import matplotlib.pyplot as plt

def myfunction(**parameters):
    fig, axs = plt.subplots(**parameters)
    return fig, axs

fig, axs = myfunction(figsize=(6,5))

因此,为了使类的使用有意义,人们可能希望以某种方式存储它,然后使用它的属性或方法。

import matplotlib.pyplot as plt

class MyClass():
    def __init__(self, **parameters):
        self.fig, self.axs = plt.subplots(**parameters)

myclass = MyClass(figsize=(6,5))
fig = myclass.fig
axs = myclass.axs

关于python - 创建一个类来生成子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51545005/

相关文章:

Python RE - 用于匹配带有转义引号的类 printf 格式字符串的正则表达式

python - 在 Raspberry PI 启动时运行 OpenVINO Python 脚本

python - matplotlib 绘制多个散点图,每个散点图由不同的第三变量着色

python - matplotlib 中图像中的标签问题

python - Matplotlib - Jupyter 笔记本

python - Django 安装到错误的 python 版本

Python 脚本是否应该以换行结尾? Pylint自相矛盾?

image - 如何强制python编写3 channel png图像

python - 如何在图中表示非常大和非常小的值

python - 无法弄清楚字符串替换在 Python 3.x 中的工作原理