1

I am trying to create a figure with two subplots by using a loop, but the data for each keeps getting plotted to both subplots. Here is an example of what I have:

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)

And, when this is run, it gives me two subplots with all 4 lines on both. But, what I am trying to achieve is having line_1 and line_2 on the first subplot and line_3 and line_4 on the second subplot.

If anyone has a fix, please let me know.

1 Answer 1

1

So, after playing around with it, I found a solution:

In the __init__ block of my class:

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)

I changed it to:

class Plots:
    def __init__(self):
        self.list_of_lines = []

    def append_line(self, newLine):
            self.list_of_lines.append(newLine)

And that fixed the issue. I'm not sure why, but something with defining the class variables the original way I did brought up the issue. Regardless, it is fixed. Hopefully this will help others that are trying to create plots with classes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.