Анимация метода Монте-Карло Пи цветные точки по-разному - PullRequest
0 голосов
/ 03 апреля 2020

Я хочу получить анимацию моего графика моих результатов метода m c, вычисляющего pi; но точки внутри круга окрашены не так, как другие. Как я могу это сделать? Пока это мой код:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

def punkt_im_quadrat(a,N): #a is length of square, N number of dots
"""generates random point in [0,a)x[0,a)"""
    x = a * np.random.random_sample((N,2))
    return x #[x,y]

def kreis(radius):
    return np.sqrt(radius - x**2)
x = np.linspace(0,1,100)

#create array of N=10 dots
punkte = punkt_im_quadrat(1,10) #a=1, so radius of circle is one


treffer = [i for i in punkte if i[1] <= np.sqrt(1 - i[0]**2)] #dots in circle
treffer = np.array(treffer)

außerhalb = [i for i in punkte if i not in treffer] #dots not in circle
außerhalb = np.array(außerhalb)


pi = 4 * len(treffer) / np.shape(punkte)[0] 

fig = plt.figure()
fig, ax = plt.subplots()
ax.plot(x,kreis(1))
ax.set_xlim(0,1)
ax.set_ylim(0,1)
ax.set(title=r"MC Sampling for $\pi$", 
      ylabel="y-axis",
      xlabel="x-axis")
#colors = ["r" if [punkte[i][0],punkte[i][1]] in treffer else "b"]
graph, = ax.plot([],[], "ro")

def animate(i):
    graph.set_data((punkte[:i,0],), (punkte[:i,1],))
    return graph,


animation = FuncAnimation(fig, func=animate, frames = range(np.shape(punkte)[0]), interval=20, repeat = False)
plt.show()

Как видите, я пытался изменить цвета, используя закомментированный оператор if цвета; но тогда он говорит
IndexError: массивы, используемые в качестве индексов, должны иметь целочисленный (или логический) тип

Затем я подумал, что мог бы сделать оператор if в анимированной функции, чтобы определить, где находится точка. Но при использовании graph.set_color он меняет цвет всех точек.

Я был бы очень рад, если бы кто-нибудь смог мне помочь.
Заранее спасибо!

1 Ответ

1 голос
/ 03 апреля 2020

Все маркеры в plot имеют одинаковый цвет, поэтому не могут работать. Если вы хотите разные цвета для разных точек, вам нужно использовать scatter()

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

def punkt_im_quadrat(a,N): #a is length of square, N number of dots
    """generates random point in [0,a)x[0,a)"""
    x = a * np.random.random_sample((N,2))
    return x #[x,y]

def kreis(radius):
    return np.sqrt(radius - x**2)
x = np.linspace(0,1,100)

#create array of N=10 dots
punkte = punkt_im_quadrat(1,10) #a=1, so radius of circle is one


treffer = [i for i in punkte if i[1] <= np.sqrt(1 - i[0]**2)] #dots in circle
treffer = np.array(treffer)

außerhalb = [i for i in punkte if i not in treffer] #dots not in circle
außerhalb = np.array(außerhalb)

colors = np.array(["r" if i[1] <= np.sqrt(1 - i[0]**2) else "b" for i in punkte])


pi = 4 * len(treffer) / np.shape(punkte)[0] 

fig, ax = plt.subplots()
ax.plot(x,kreis(1))
ax.set_xlim(0,1)
ax.set_ylim(0,1)
ax.set(title=r"MC Sampling for $\pi$", 
      ylabel="y-axis",
      xlabel="x-axis")
graph = ax.scatter([],[], marker='o', s=30)

def animate(i):
    graph.set_offsets(punkte[:i,:])
    graph.set_facecolor(colors[:i])
    return graph,


animation = FuncAnimation(fig, func=animate, frames = range(np.shape(punkte)[0]), interval=20, repeat = False)
...