【问题标题】:Creating subplots from lists with loop. Causes data to plot to both subplots使用循环从列表创建子图。导致数据绘制到两个子图
【发布时间】:2019-08-08 16:53:13
【问题描述】:

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

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

如果有人有解决办法,请告诉我。

【问题讨论】:

    标签: python loops matplotlib


    【解决方案1】:

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

    在我班级的__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)
    

    这就解决了问题。我不知道为什么,但是以我原来的方式定义类变量的方式提出了这个问题。无论如何,它是固定的。 希望这将有助于其他尝试使用类创建图的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 2014-05-18
      • 2020-08-04
      • 2018-03-16
      • 1970-01-01
      相关资源
      最近更新 更多