每次调用类中的函数时增加计数器

2024-05-06 12:46:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类有很多绘图函数。我的意图是使用matplotlib的subplot方法将所有绘图分组到一个图像中,具体取决于我调用了多少个函数。你知道吗

我尝试了如下的方法(这是我程序的一个简短版本),但我不知道为什么它不起作用。你知道吗

感谢您的帮助。提前谢谢。你知道吗

import itertools
import numpy as np
from matplotlib import pyplot as plt

class Base(object):
    def __init__(self, a, multiPlot=True, numColGraph=None, numRowGraph=None,
                 figSize=None, DPI=None, num=None):

        self.a = a
        self.x = np.linspace(0, 5)

        if multiPlot:
        self.nCG = numColGraph
            self.nRG = numRowGraph
        else:
            self.nCG = 1
            self.nRG = 1

        if figSize and DPI:
            self.thePlot = plt.figure(figsize=figSize, dpi=DPI)

        if num == 0:
            self.plotId = itertools.count(1)

    def createPlot1(self):
        y = self.x**(a/2)
        self.thePlot.add_subplot(self.nRG, self.nCG, next(self.plotId))
        plt.plot(self.x, y, label=str(self.a)+'/2')

    def createPlot2(self):
        y = self.x**a
        self.thePlot.add_subplot(self.nRG, self.nCG, next(self.plotId))
        plt.plot(self.x, y, label=self.a)

    def createPlot3(self):
        y = self.x**(2*a)
        self.thePlot.add_subplot(self.nRG, self.nCG, next(self.plotId))
        plt.plot(self.x, y, label=str(self.a)+'*2')


if __name__ == "__main__":

    A = np.linspace(0, 2, 5)

    for i, a in enumerate(A):
        Instance = Base(a, numColGraph=3, numRowGraph=len(A),
                 figSize=(12,10), DPI=100, num=i)
        Instance.createPlot1()
        Instance.createPlot2()
        Instance.createPlot3()

    plt.show()

Tags: instanceimportselfnoneifdefnpplt
1条回答
网友
1楼 · 发布于 2024-05-06 12:46:25

至少,您有未定义的变量。我看到这种模式(或类似的模式)三次:

y = self.x**(2*a)

但在这些情况下,您都没有定义a。也许你的意思是:

y = self.x**(2*self.a)

相关问题 更多 >