简体   繁体   English

如何在 Python 3 中的同一绘图上绘制来自多个对象的实例属性

[英]How to plot instance attributes from multiple objects on same plot in Python 3

I have a class that generates lists of data from mathematical equations I formulated to model a system over time.我有一个课程,它从我制定的数学方程生成数据列表,以随着时间的推移对系统进行建模。 The class can take different numbers for the different variables in the equations, therefore you can create objects from the class that have different model output.该类可以为方程中的不同变量采用不同的数字,因此您可以从具有不同模型输出的类创建对象。 I would like to plot the output from different objects on the same plot, but when I try to do so I get the following error: ValueError: x and y must have same first dimension, but have shapes (5,) and (10,) .我想在同一个图上绘制不同对象的输出,但是当我尝试这样做时,我收到以下错误: ValueError: x and y must have same first dimension, but have shapes (5,) and (10,) I am plotting using matplotlib.我正在使用 matplotlib 进行绘图。 An example of what the code looks like is here:代码示例如下:

import matplotlib.pyplot as plt

class Foo:
    def __init__(self, x=[1,2,3,4,5], y=[], var1=None, var2=None):
        self.x = x
        self.y = y
        self.var1 = var1
        self.var2 = var2

    def calculate_y(self, index):
        return (self.var1 + self.var2) * self.x[index]

    def run_calculation(self):
        for i in range (0, len(self.x)):
            self.y.append(self.calculate_y(i))

obj1 = Foo(var1 = 1, var2 = 2)
obj2 = Foo(var1 = 3, var2 = 4)

obj1.run_calculation()
obj2.run_calculation()

plt.figure(1)
plt.plot(obj1.x, obj1.y)
plt.plot(obj2.x, obj2.y)
plt.show()

I am using the lists generated by the class methods from the individual objects to plot.我正在使用由单个对象的类方法生成的列表进行绘图。 Any idea why I'm getting this error and am unable to plot?知道为什么我会收到此错误并且无法绘图吗? Thanks in advance.提前致谢。

Your default argument of an empty list, for some obscure reason, makes it so the same list is appended (get the explanation here ).由于某些晦涩的原因,空列表的默认参数使它附加了相同的列表(在此处获取解释)。 Change this line so both instances work on separate lists:更改此行,以便两个实例都在单独的列表上工作:

self.y = y.copy()

Here's your output:这是你的输出: 在此处输入图片说明

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM