user9421252
user9421252

Reputation: 17

Multiple Figures in Matplotlib - Nested Loop

First I want to generate a plot, colorized by how close the average data is to the goal. (the real program is a machine learning algorithm trying to learn weights). I want to generate a histogram for each data point in the final plot, but I can't seem to generate the plots independently. Any help would be greatly appreciated.

import matplotlib.pyplot as plt
import numpy as np

def generateData(goal):
    x=[_ for _ in range(20)]
    y=[10+np.random.exponential()*5 for _ in range(100)]
    return x,y

def drawHistogram(data,nBins):
    plt.figure(2)
    plt.hist(diffs,nBins)
    plt.draw()
    plt.show()

sweep=np.linspace(10,20,4)

for goal in sweep:
    for gw2 in sweep:

        diffs=[]

        for i in range(10):
            data=generateData(goal)
            diffs.append(goal-np.mean(data[1]))


        #generate plot
        plt.figure(1)
        clr=(abs(np.mean(diffs))/goal,0,0)
        plt.plot([goal], [gw2], marker="s", mew='1', ms='35', color=clr)

        drawHistogram(diffs,5) ##Comment this line out to see what the final graph should look like

plt.figure(1)
plt.draw()
plt.show()

Upvotes: 0

Views: 1033

Answers (1)

David Owens
David Owens

Reputation: 675

This generates 17 individual histograms and 1 final figure with the red squares.

import matplotlib.pyplot as plt
import numpy as np

def generateData(goal):
    x=[_ for _ in range(20)]
    y=[10+np.random.exponential()*5 for _ in range(100)]
    return x,y

def drawHistogram(data,nBins):
    plt.figure()
    plt.hist(diffs,nBins)

sweep=np.linspace(10,20,4)

for goal in sweep:
    for gw2 in sweep:

        diffs=[]

        for i in range(10):
            data=generateData(goal)
            diffs.append(goal-np.mean(data[1]))

        #generate plot
        plt.figure(1)
        clr=(abs(np.mean(diffs))/goal,0,0)
        plt.plot([goal], [gw2], marker="s", mew='1', ms='35', color=clr)

        drawHistogram(diffs,5) ##Comment this line out to see what the final graph should look like

plt.draw()
plt.show()

Upvotes: 1

Related Questions