我尝试使用循环创建一个包含两个子图的图形,但每个子图的数据不断绘制到两个子图。这是我所拥有的示例:
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_1
和 line_2
,在第一个子图上使用 line_3
和 line_4
第二个子图。
如果有人有解决办法,请告诉我。
最佳答案
所以,在尝试之后,我找到了一个解决方案:
在我的类的 __init__
block 中:
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)
这解决了问题。我不知道为什么,但是用我原来的方式定义类变量时提出了这个问题。无论如何,它是固定的。 希望这能帮助其他尝试用类创建绘图的人。
关于python - 使用循环从列表创建子图。使数据绘制到两个子图上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57417374/