0

I'm trying to make a dynamically updating graph in Matplotlib for a research simulation. Based on other threads, I've gotten to here in my code:

import math
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import time
from datetime import datetime
%matplotlib inline

def get_position(n):
    pos = 0.5
    tie = 0
    self = False
    for strat in strategies:
        if n > strat:
            pos = pos + 1
        elif n == strat:
            if self == False:
                self = True
            else:
                tie = tie + 1
    return pos + (tie/len(strategies))

def get_y(n):
    ux = 1 + (2 * 5 * n) - (n * n)
    vy = (1 - (get_position(n)/len(strategies))/3.6) * (1 + (get_position(n)/len(strategies))/3)
    return ux * vy

def update(bubbles, landscape, x, y, strategies):
    for i in range(len(strategies)):
        toWait = wait_times[i]
        if toWait > 0:
            wait_times[i] = wait_times[i] - 1
            continue
        best = max(y)
        indices = [k for k, j in enumerate(y) if j == best]
        choice = random.choice(indices)
        choice = x[choice]
        strategies[i] = choice
        wait_times[i] = random.randint(0, 10)
        positions = []
        for val in x:
            positions.append(get_position(val))
        positions = np.array(positions)
        ux = 1 + (2 * 5 * x) - (x * x)
        vy = (1 - (positions/len(strategies))/3.6) * (1 + (positions/len(strategies))/3)
        y1 = ux * vy
        strat_x = np.sort(strategies)
        strat_y = []
        for strat in strat_x:
            strat_y.append(get_y(strat))
        bubbles.set_xdata(strat_x)
        bubbles.set_ydata(strat_y)
        landscape.set_xdata(x)
        landscape.set_ydata(y1)
        fig.canvas.draw()
        # ax.clear()
        # ax.plot(strat_x, strat_y, 'ro', fillstyle='none', markersize=10)
        # ax.plot(x, y)

fig = plt.figure(num=None, figsize=(10, 5), dpi=80)
ax = fig.add_subplot(1, 1, 1)

strategies = []
wait_times = []
for i in range(20):
    strategies.append(round((random.random() * 4 + 3), 2))
    wait_times.append(random.randint(0, 10))

x = np.arange(3.0, 7.0, 0.01)
positions = []
for val in x:
    positions.append(get_position(val))
positions = np.array(positions)
ux = 1 + (2 * 5 * x) - (x * x)
vy = (1 - (positions/len(strategies))/3.6) * (1 + (positions/len(strategies))/3)
y = ux * vy
strat_x = np.sort(strategies)
strat_y = []
for strat in strat_x:
    strat_y.append(get_y(strat))
bubbles, = ax.plot(strat_x, strat_y, 'ro', fillstyle='none', markersize=10)
landscape, = ax.plot(x, y)

for i in range(0, 10):
    update(bubbles, landscape, x, y, strategies)
    #time.sleep(1)

The output is correct, but only shows the last (in this case 10th) iteration of the graph. Ideally, this would be running in a while true loop when it's functional.

0 Answers0