Saturday, May 29, 2021

Animating matplotlib

# https://www.youtube.com/watch?v=7RgoHTMbp4A

# Draw Scatter Diagram & Regression Line

import matplotlib.pyplot as plt

import numpy as np

from sklearn.linear_model import LinearRegression

import random


reg = LinearRegression()

x_values, y_values = [], []

plt.xlim(0, 100)

plt.ylim(0, 100)


for i in range(95):

  plt.clf()

  x_values.append(random.randint(0, 100))

  y_values.append(random.randint(0, 100))

  x = np.array(x_values)

  x = x.reshape(-1, 1)

  y = np.array(y_values)

  y = y.reshape(-1, 1)


  if i % 5 == 0 or i == 94:

    reg.fit(x, y)

    plt.scatter(x_values, y_values, color='brown')

    plt.plot(list(range(100)), reg.predict(np.array([x for x in range(100)]).reshape(-1, 1))) 

    plt.pause(0.0001)

plt.show()


# Draw histogram

import matplotlib.pyplot as plt

import random


values = [0] * 50

plt.xlim(0, 50)

plt.ylim(0, 100)


for i in range(50):

  values[i] = random.randint(0, 100)

  plt.bar(list(range(50)), values)

  plt.pause(0.0001)

plt.show()


# Draw histogram of heads and tails in 100000 throws

import matplotlib.pyplot as plt
import random

heads_tails = [0, 0]

for i in range(100000):
  if i % 50 == 0:
    heads_tails[random.randint(0, 1)] += 1
    #print(heads_tails)
    plt.bar([0, 1], heads_tails, color=("blue", "red"))
    plt.pause(0.0001)

plt.show()


# Draw histogram to simulate throw of die 100000 times

import matplotlib.pyplot as plt
import random

dice = [0, 0, 0, 0, 0, 0]

for i in range(100000):
  if i % 50 == 0:
    dice[random.randint(0, 5)] += 1
    plt.bar([1, 2, 3, 4, 5, 6], dice, color=("blue", "red"))
    plt.pause(0.0001)

plt.show()

No comments:

Post a Comment