peterxz
peterxz

Reputation: 874

Python holding onto a matplotlib plot to pass in several functions before showing

What I am trying to do is to "initialise" a plot, and pass in datasets via a function to plot onto this graph. Then when I am happy the plot contains everything I want to show, I show it. How could I do this?

import numpy as np
from matplotlib import pyplot as plt

def plot_polynomials(solutions, train_x, train_y):
    x = np.arange(-5, 6)
    plt.plot(x, genPoly(x, solutions))
    plt.show()

data = read_coords("data.csv")
data = np.asarray(data)
system,solution = pol_regression(data[:,0], data[:,1], 2)
plot_polynomials(solution, data[:,0], data[:,1])

#I want to do something like this but im not sure what plot_polynomials() should contain
#to be able to "hold onto" the constructed graph before showing.
#I need all polynomials on the same graph
for i in range(11):
    system,solution = pol_regression(data[:,0], data[:,1], i)
    plot_polynomials(solution, data[:,0], data[:,1])

Upvotes: 0

Views: 254

Answers (1)

Bill Chen
Bill Chen

Reputation: 1749

I am not quite sure what you mean 'hold onto', but if you want to plot everything on one graph here is what you should do:

  1. If you want to stack all your regression lines:

    plt.figure()
    for i in range(11):
        system,solution = pol_regression(data[:,0], data[:,1], i)
        x = np.arange(-5, 6)
        plt.plot(x, genPoly(x, solutions))
    
    plt.show()
    
  2. if you want your plots, 11 of them on one figure (11 small figures):

    for i in range(11):
        system,solution = pol_regression(data[:,0], data[:,1], i)
        plt.subplot(11, 1, i) # 11 rows, 1 column, ith graph
        x = np.arange(-5, 6)
        plt.plot(x, genPoly(x, solutions))
    plt.show()
    

Hope this helps.

Upvotes: 1

Related Questions