[英]How to plot instance attributes from multiple objects on same plot in Python 3
我有一个课程,它从我制定的数学方程生成数据列表,以随着时间的推移对系统进行建模。 该类可以为方程中的不同变量采用不同的数字,因此您可以从具有不同模型输出的类创建对象。 我想在同一个图上绘制不同对象的输出,但是当我尝试这样做时,我收到以下错误: ValueError: x and y must have same first dimension, but have shapes (5,) and (10,)
。 我正在使用 matplotlib 进行绘图。 代码示例如下:
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()
我正在使用由单个对象的类方法生成的列表进行绘图。 知道为什么我会收到此错误并且无法绘图吗? 提前致谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.