从带有循环的列表创建子图.使数据绘制到两个子图



我正在尝试使用循环创建一个具有两个子图的图形,但是每个子图的数据不断绘制到两个子图上。这是我拥有的示例:

import matplotlib.pyplot as plt
my_graph = []
plot_1 = []
plot_2 = []
line_1 = 1
line_2 = 2
line_3 = 3
line_4 = 4
class Plots:
def __init__(self, list_of_lines = []):
self.list_of_lines = list_of_lines
def append_line(self, newLine):
self.list_of_lines.append(newLine)
plot_1 = Plots()
plot_1.append_line(line_1)
plot_1.append_line(line_2)
my_graph.append(plot_1)
plot_2 = Plots()
plot_2.append_line(line_3)
plot_2.append_line(line_4)
my_graph.append(plot_2)
def plotting(graph):
fig, axes = (ax1, ax2) = plt.subplots(2, figsize=(8,6))
for x in range(len(graph)):
for line in graph[x].list_of_lines:
axes[x].axhline(y=line)

plotting(my_graph)

而且,当它运行时,它给了我两个子图,所有 4 行都在上面。但是,我试图实现的是第一个子图的line_1line_2,第二个子图line_3line_4

如果有人有修复,请告诉我。

所以,在玩了一下之后,我找到了一个解决方案:

在我类的__init__块中:

class Plots:
def __init__(self, list_of_lines = []):
self.list_of_lines = list_of_lines
def append_line(self, newLine):
self.list_of_lines.append(newLine)

我把它改成:

class Plots:
def __init__(self):
self.list_of_lines = []
def append_line(self, newLine):
self.list_of_lines.append(newLine)

这解决了这个问题。我不确定为什么,但是以原始方式定义类变量的东西提出了这个问题。无论如何,它是固定的。 希望这将帮助其他试图用类创建情节的人。