I need help to generate this graph, especially with domains limits
and the arrow indicating the domain
all I can do is generate the domains name but not the limits and arrow
The following code will produce something like what you require:
from matplotlib import pyplot as plt
from matplotlib.patches import Wedge
import numpy as np
labels = ["Obésité\nmassive", "Obésité", "Surpoids", "Normal", "Maigreur"]
innerlabels = [">40", "30 à 40", "25 à 30", "18,5 à 25", "< 18,5"]
colours = ["red", "darkorange", "orange", "green", "blue"]
fig, ax = plt.subplots(figsize=(6, 6), dpi=200)
theta = 0
dtheta = 180 / len(labels)
width = 0.35
def pol2cart(rho, phi):
x = rho * np.cos(phi)
y = rho * np.sin(phi)
return(x, y)
patches = []
for i in range(len(labels)):
# outer wedge
wedge = Wedge(0, r=1, width=width, theta1=theta, theta2=(theta + dtheta), fc=colours[i], alpha=0.6, edgecolor="whitesmoke")
ax.add_patch(wedge)
# inner wedge
wedge = Wedge(0, r=1 - width, width=width, theta1=theta, theta2=(theta + dtheta), fc=colours[i], edgecolor="whitesmoke")
ax.add_patch(wedge)
theta += dtheta
# add text label
tr = 1 - (width / 2)
ta = theta - dtheta / 2
x, y = pol2cart(tr, np.deg2rad(ta))
textangle = -np.fmod(90 - ta, 180)
ax.text(x, y, labels[i], rotation=textangle, va="center", ha="center", color="white", fontweight="bold")
# inner labels
tr = (1 - width) - (width / 2)
x, y = pol2cart(tr, np.deg2rad(ta))
textangle = -np.fmod(90 - ta, 180)
ax.text(x, y, innerlabels[i], rotation=textangle, va="center", ha="center", color="white")
ax.set_xlim([-1, 1])
ax.set_ylim([0, 1])
ax.set_axis_off()
ax.set_aspect("equal")
def bmiposition(bmi):
"""
Get angular position of BMI arrow.
"""
from scipy.interpolate import interp1d
bmiranges = [(0, 18.5), (18.5, 25), (25, 30), (30, 40), (40, 80)]
angrange = [(180 - dtheta * i, 180 - dtheta * (i + 1)) for i in range(len(bmiranges))]
interpfuncs = []
for i in range(len(bmiranges)):
interpfuncs.append(interp1d(bmiranges[i], angrange[i], kind="linear"))
bmiang = np.piecewise(
bmi,
[bmiranges[i][0] < bmi <= bmiranges[i][1] for i in range(len(bmiranges))],
interpfuncs,
)
return bmiang
bmi = 22.5 # set BMI
# add arrow
pos = bmiposition(bmi) # get BMI angle
x, y = pol2cart(0.25, np.deg2rad(pos))
ax.arrow(0, 0, x, y, head_length=0.125, width=0.025, fc="k")
ax.plot(0, 0, 'ko', ms=10) # circle at origin
giving:
Related
The following code :
import matplotlib.pyplot as plt
import numpy as np
def autopct_format(values):
def my_format(pct):
total = sum(values)
val = int(round(pct*total/100.0)/1000000)
if val == 0:
return ""
else:
return '{:.1f}%\n({v:,d})'.format(pct, v=val)
return my_format
fig, ax = plt.subplots(1,1,figsize=(10,10),dpi=100,layout="constrained")
ax.axis('equal')
width = 0.3
#Color
A, B, C=[plt.cm.Blues, plt.cm.Reds, plt.cm.Greens]
#OUTSIDE
cin = [A(0.5),A(0.4),A(0.3),B(0.5),B(0.4),B(0.3),B(0.2),B(0.1), C(0.5),C(0.4),C(0.3)]
Labels_Smalls = ['groupA', 'groupB', 'groupC']
labels = ['A.1', 'A.2', 'A.3', 'B.1', 'B.2', 'C.1', 'C.2', 'C.3',
'C.4', 'C.5']
Sizes_Detail = [4,3,5,6,5,10,5,5,4,6]
Sizes = [12,11,30]
pie2, _ ,junk = ax.pie(Sizes_Detail ,radius=1,
labels=labels,labeldistance=0.85,
autopct=autopct_format(Sizes_Detail) ,pctdistance = 1.15,
colors=cin)
for ea, eb in zip(pie2, _):
mang =(ea.theta1 + ea.theta2)/2
tourner = 360 - mang
eb.set_rotation(mang+tourner) # rotate the label by (mean_angle + 270)
eb.set_va("center")
eb.set_ha("center")
plt.setp(pie2, width=width, edgecolor='white')
#INSIDE
pie, _, junk = ax.pie(Sizes, radius=1-width,
autopct=autopct_format(Sizes) ,pctdistance = 0.8,
colors = [A(0.6), B(0.6), C(0.6)])
plt.setp(pie, width=width, edgecolor='white')
plt.margins(0,0)
bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"),
bbox=bbox_props, zorder=3, va="center")
for i, p in enumerate(pie):
ang = (p.theta2 - p.theta1)/2. + p.theta1
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
kw["arrowprops"].update({"connectionstyle": connectionstyle})
ax.annotate(Labels_Smalls[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
horizontalalignment=horizontalalignment, **kw)
for ea, eb in zip(pie, _):
mang =(ea.theta1 + ea.theta2)/2. # get mean_angle of the wedge
#print(mang, eb.get_rotation())
tourner = 360 - mang
eb.set_rotation(mang+tourner) # rotate the label by (mean_angle + 270)
eb.set_va("center")
eb.set_ha("center")
gives the following output :
But It does only link the outside pie and not the inside one, so how would I do the same chart but with the arrow linking the inside pie to the bbox ?
The code below animates a bar chart and associated label values. The issue I'm having is positioning the label when the integer is negative. Specifically, I want the label to be positioned on top of the bar, not inside it. It's working for the first frame but the subsequent frames of animation revert back to plotting the label inside the bar chart for negative integers.
def autolabel(rects, ax):
# Get y-axis height to calculate label position from.
ts = []
(y_bottom, y_top) = ax.get_ylim()
y_height = y_top - y_bottom
for rect in rects:
height = 0
if rect.get_y() < 0:
height = rect.get_y()
else:
height = rect.get_height()
p_height = (height / y_height)
if p_height > 0.95:
label_position = height - (y_height * 0.05) if (height > -0.01) else height + (y_height * 0.05)
else:
label_position = height + (y_height * 0.01) if (height > -0.01) else height - (y_height * 0.05)
t = ax.text(rect.get_x() + rect.get_width() / 2., label_position,
'%d' % int(height),
ha='center', va='bottom')
ts.append(t)
return ts
def gradientbars(bars, ax, cmap, vmin, vmax):
g = np.linspace(vmin,vmax,100)
grad = np.vstack([g,g]).T
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
ims = []
for bar in bars:
bar.set_facecolor('none')
im = ax.imshow(grad, aspect="auto", zorder=0, cmap=cmap, vmin=vmin, vmax=vmax, extent=(xmin,xmax,ymin,ymax))
im.set_clip_path(bar)
ims.append(im)
return ims
vmin = -6
vmax = 6
cmap = 'PRGn'
data = np.random.randint(-5,5, size=(10, 4))
x = [chr(ord('A')+i) for i in range(4)]
fig, ax = plt.subplots()
ax.grid(False)
ax.set_ylim(vmin, vmax)
rects = ax.bar(x,data[0])
labels = autolabel(rects, ax)
imgs = gradientbars(rects, ax, cmap=cmap, vmin=vmin, vmax=vmax)
def animate(i):
for rect,label,img,yi in zip(rects, labels, imgs, data[i]):
rect.set_height(yi)
label.set_text('%d'%int(yi))
label.set_y(yi)
img.set_clip_path(rect)
anim = animation.FuncAnimation(fig, animate, frames = len(data), interval = 500)
plt.show()
It's working for the first frame.
You call autolabel(rects, ax) in the first plot, so the label is well placed.
The subsequent frames of animation revert back to plotting the label inside the bar chart for negative integers.
The label position of subsequent frames is set by label.set_y(yi). yi is from data[i], you didn't consider the negative value here.
I create a function named get_label_position(height) to calculate the right label position for give height. It uses a global variable y_height. And call this function before label.set_y().
import matplotlib.pyplot as plt
from matplotlib import animation
import pandas as pd
import numpy as np
def get_label_position(height):
p_height = (height / y_height)
label_position = 0
if p_height > 0.95:
label_position = height - (y_height * 0.05) if (height > -0.01) else height + (y_height * 0.05)
else:
label_position = height + (y_height * 0.01) if (height > -0.01) else height - (y_height * 0.05)
return label_position
def autolabel(rects, ax):
# Get y-axis height to calculate label position from.
ts = []
(y_bottom, y_top) = ax.get_ylim()
y_height = y_top - y_bottom
for rect in rects:
height = 0
if rect.get_y() < 0:
height = rect.get_y()
else:
height = rect.get_height()
p_height = (height / y_height)
if p_height > 0.95:
label_position = height - (y_height * 0.05) if (height > -0.01) else height + (y_height * 0.05)
else:
label_position = height + (y_height * 0.01) if (height > -0.01) else height - (y_height * 0.05)
t = ax.text(rect.get_x() + rect.get_width() / 2., label_position,
'%d' % int(height),
ha='center', va='bottom')
ts.append(t)
return ts
def gradientbars(bars, ax, cmap, vmin, vmax):
g = np.linspace(vmin,vmax,100)
grad = np.vstack([g,g]).T
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
ims = []
for bar in bars:
bar.set_facecolor('none')
im = ax.imshow(grad, aspect="auto", zorder=0, cmap=cmap, vmin=vmin, vmax=vmax, extent=(xmin,xmax,ymin,ymax))
im.set_clip_path(bar)
ims.append(im)
return ims
vmin = -6
vmax = 6
cmap = 'PRGn'
data = np.random.randint(-5,5, size=(10, 4))
x = [chr(ord('A')+i) for i in range(4)]
fig, ax = plt.subplots()
ax.grid(False)
ax.set_ylim(vmin, vmax)
rects = ax.bar(x,data[0])
labels = autolabel(rects, ax)
imgs = gradientbars(rects, ax, cmap=cmap, vmin=vmin, vmax=vmax)
(y_bottom, y_top) = ax.get_ylim()
y_height = y_top - y_bottom
def animate(i):
for rect,label,img,yi in zip(rects, labels, imgs, data[i]):
rect.set_height(yi)
label.set_text('%d'%int(yi))
label.set_y(get_label_position(yi))
img.set_clip_path(rect)
anim = animation.FuncAnimation(fig, animate, frames = len(data), interval = 500)
plt.show()
This program reads an image which is in location C:/Square.png and lines are plotted over it. The plot title is also defined. I want to show this whole image in tkinter window. How do I do it?
This is the image. The name has to be changed and we can run the code.
https://imgur.com/RkV02yY
import math
import matplotlib.pyplot as plt
def plot_output(opt_w, opt_h, n_x, n_y):
y_start, y_end = 100, 425
x_start, x_end = 25, 400
img = plt.imread("C:/Square.png") #Please change the location
fig, ax = plt.subplots(figsize=(10, 10))
plt.axis('off')
ax.imshow(img)
x_interval = (x_end - x_start)/n_x*2
h_x = range(x_start, x_end, 5)
for i in range(0,int(n_y)):
if i != 0:
ax.plot(h_x, [y_start + (y_end-y_start)/n_y*i]*len(h_x), '--', linewidth=5, color='firebrick')
plt.title(str(int(n_x*n_y)) + ' ABCD\n'+'TYUI:'+str(opt_w)+', Yummy:'+str(opt_h))
def get_get(min_w, min_h, max_w, max_h, PL, PH, min_t, max_t, cost_m, cost_a):
x = 1
if max_w < PL:
x = math.ceil(PL / max_w)
cost_rest = cost_m * PL * PH * (max_t + min_t) / 2 + cost_a * PH * x
cost_y = float("inf")
y = None
if min_h == 0:
min_h = 1
for i in range(math.ceil(PH / max_h), math.floor(PH / min_h)+1):
tmp_cost = cost_m * PL * PH * (max_t - min_t) / 2 / i + cost_a * PL * i
if tmp_cost < cost_y:
cost_y = tmp_cost
y = i
opt_w, opt_h, opt_cost = PL/x, PH/y, cost_rest + cost_y
plot_output(opt_w, opt_h, x, y)
return opt_w, opt_h, opt_cost
PL=30
PH=10
min_t=0.1
max_t=0.3
cost_m=0.1
cost_a=0.1
min_w=0.5
min_h=0.5
max_w=4
max_h=3
get_get(min_w, min_h, max_w, max_h, PL, PH, min_t, max_t, cost_m, cost_a)
You need to add plt.show()
import math
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use("Tkagg")
def plot_output(opt_w, opt_h, n_x, n_y):
y_start, y_end = 100, 425
x_start, x_end = 25, 400
img = plt.imread("C:/Square.png") #Please change the location
fig, ax = plt.subplots(figsize=(10, 10))
plt.axis('off')
ax.imshow(img)
x_interval = (x_end - x_start)/n_x*2
h_x = range(x_start, x_end, 5)
for i in range(0,int(n_y)):
if i != 0:
ax.plot(h_x, [y_start + (y_end-y_start)/n_y*i]*len(h_x), '--', linewidth=5, color='firebrick')
plt.title(str(int(n_x*n_y)) + ' ABCD\n'+'TYUI:'+str(opt_w)+', Yummy:'+str(opt_h))
plt.show()
def get_get(min_w, min_h, max_w, max_h, PL, PH, min_t, max_t, cost_m, cost_a):
x = 1
if max_w < PL:
x = math.ceil(PL / max_w)
cost_rest = cost_m * PL * PH * (max_t + min_t) / 2 + cost_a * PH * x
cost_y = float("inf")
y = None
if min_h == 0:
min_h = 1
for i in range(math.ceil(PH / max_h), math.floor(PH / min_h)+1):
tmp_cost = cost_m * PL * PH * (max_t - min_t) / 2 / i + cost_a * PL * i
if tmp_cost < cost_y:
cost_y = tmp_cost
y = i
opt_w, opt_h, opt_cost = PL/x, PH/y, cost_rest + cost_y
plot_output(opt_w, opt_h, x, y)
return opt_w, opt_h, opt_cost
PL=30
PH=10
min_t=0.1
max_t=0.3
cost_m=0.1
cost_a=0.1
min_w=0.5
min_h=0.5
max_w=4
max_h=3
get_get(min_w, min_h, max_w, max_h, PL, PH, min_t, max_t, cost_m, cost_a)
Edit: I forgot to change the backend to tkinter
My planets orbits are not matching up with my circular paths im plotting of the orbits, I have matched in my for loop the distance for every planet with the distance they are from the center.(image is attached)
from pylab import *
from matplotlib.animation import *
Here is where I am defining the circes I will plot to show the paths of the orbits at the "def circle..."
def circle(x0,y0,R,N) :
''' create circle, given center x0,y0, input radius R,
and number of points N, then
output arrays of x and y coordinates '''
theta = linspace(0.0,2.0*pi,N)
x = R * cos(theta) + x0
y = R * sin(theta) + y0
return x,y
a= array([.39,.72,1,1.52,5.20,9.54,19.2,30.1]) #astronomical units of #the planets in order of the planets(i.e mercury, venus, earth,mars...)
period = a**(3.0/2.0)
I am taking the distane of the planets and inputting them in array, to be able to use a for loop to graph the circles.
#distance of the planets
d= array([390,790,980, 1520,5200,9540,19200,30100])#same order of the #planets as well
#attributes of the sun
x0 =0
y0 = 0
r_s=70*1.2#actual earth radius is 695e6
#radius of the planets
r_Ear = 63.781#e in m {for all the planets}
r_Merc= 24
r_Ven = 60
r_Mars= 33.9
r_Jup = 700
r_Sat = 582
r_Ura = 253
r_Nep = 246
the actual distance of the planets
#Distance of the planets
d_Ear = 1000#152
d_Merc= 390#70
d_Ven = 790#109
d_Mars= 1520#249
d_Jup = 5200#816
d_Sat = 9540#1514
d_Ura = 19200#3003
d_Nep = 30100#4545
fig = plt.figure()
ax = plt.axes(xlim=(-1e4-5000, 1e4+5000), ylim=(-1e4-5000, 1e4+5000), aspect=True)
This is where I am looping over, to plot 8 circles. Theres a link here to see the plot I have generated.
for i in range(8) :
x, y = circle(0.0,0.0,d[i],10000) # orbit
plot(x,y,':k')
[enter image description here][1]
The rest are the patches of the planets and the FuncAnimation.
Sun = plt.Circle((x0, y0), radius=r_s, ec='yellow', fc='yellow', lw=3)
Mercury = plt.Circle((0, 0), radius=r_Merc, ec='brown', fc='brown', lw=3)
Venus = plt.Circle((0, 0), radius=r_Ven, ec='brown', fc='brown', lw=3)
Earth = plt.Circle((0, 0), radius=r_Ear, ec='black', fc='black', lw=3)
Mars = plt.Circle((0, 0), radius=r_Mars, ec='brown', fc='brown', lw=3)
Jupiter = plt.Circle((0, 0), radius=r_Jup, ec='green', fc='green', lw=3)
Saturn = plt.Circle((0, 0), radius=r_Sat, ec='green', fc='green', lw=3)
Uranus = plt.Circle((0, 0), radius=r_Ura, ec='green', fc='green', lw=3)
Neptune = plt.Circle((0, 0), radius=r_Nep, ec='green', fc='green', lw=3)
ax.add_patch(Sun)
def init():
ax.add_patch(Earth)
ax.add_patch(Mercury)
ax.add_patch(Venus)
ax.add_patch(Mars)
ax.add_patch(Jupiter)
ax.add_patch(Saturn)
ax.add_patch(Uranus)
ax.add_patch(Neptune)
return Mercury, Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,
def animate(i):
theta = radians(i)
mx = d_Merc*np.cos(theta/period[0]) - d_Merc*np.sin(theta/period[0])
my = d_Merc*np.sin(theta/period[0]) + d_Merc*np.cos(theta/period[0])
vx = d_Ven *np.cos(theta/period[1]) - d_Ven*np.sin(theta/period[1])
vy = d_Ven *np.cos(theta/period[1]) + d_Ven*np.sin(theta/period[1])
ex = d_Ear*np.cos(theta/period[2]) - d_Ear*np.sin(theta/period[2])
ey = d_Ear*np.sin(theta/period[2]) + d_Ear*np.cos(theta/period[2])
Mx = d_Mars*np.cos(theta/period[3]) - d_Mars*np.sin(theta/period[3])
My = d_Mars*np.sin(theta/period[3]) + d_Mars*np.cos(theta/period[3])
Jx = d_Jup*np.cos(theta/period[4]) - d_Jup*np.sin(theta/period[4])
Jy = d_Jup*np.sin(theta/period[4]) + d_Jup*np.cos(theta/period[4])
Sx = d_Sat*np.cos(theta/period[5]) - d_Sat*np.sin(theta/period[5])
Sy = d_Sat*np.sin(theta/period[5]) + d_Sat*np.cos(theta/period[5])
Ux = d_Ura*np.cos(theta/period[6]) - d_Ura*np.sin(theta/period[6])
Uy = d_Ura*np.sin(theta/period[6]) + d_Ura*np.cos(theta/period[6])
Nx = d_Nep*np.cos(theta/period[7]) - d_Nep*np.sin(theta/period[7])
Ny = d_Nep*np.sin(theta/period[7]) + d_Nep*np.cos(theta/period[7])
Mercury.center = (mx, my)
Mercury._angle = i
Venus.center = (vx, vy)
Venus._angle = i
Earth.center = (ex, ey)
Earth._angle = i
Mars.center = (Mx, My)
Mars.angle =i
Jupiter.center = (Jx, Jy)
Jupiter._angle = i
Saturn.center = (Sx, Sy)
Saturn._angle = i
Uranus.center = (Ux, Uy)
Uranus.angle = i
Neptune.center = (Nx, Ny)
Neptune._angle = i
return Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune,
anim = FuncAnimation(fig, animate, init_func=init, frames=1080,
interval=25, blit=True)
plt.show()
I'm not following your math on this:
mx = d_Merc*np.cos(theta/period[0]) - d_Merc*np.sin(theta/period[0])
my = d_Merc*np.sin(theta/period[0]) + d_Merc*np.cos(theta/period[0])
You'll be more correct if you change that to this:
mx = d_Merc*np.cos(theta/period[0])
my = d_Merc*np.sin(theta/period[0])
And even more correct if you take the size of the planet into account
mx = (d_Merc+(r_Merc/2))*np.cos(theta/period[0])
my = (d_Merc+(r_Merc/2))*np.sin(theta/period[0])
That will fix your basic issue I think.
Beyond that:
d_Ear differs from Earth's value in the d array. 980 vs. 1000.
vy = d_Ven *np.cos(theta/period[1]) is not correct. That needs
to be vy = d_Ven *np.sin(theta/period[1])
As far as the code goes, you may consider using a few dictionaries to
avoid repetition like with your d array.
I am attempting to animate two different particles in matplotlib (python). I just figured out a way to animate one particle in matplotlib, but I am havign difficulties trying to get the program to work with multiple particles. Does anyone know what is wrong and how to fix it?
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(5, 4.5)
ax = plt.axes(xlim=(0, 100), ylim=(0, 100))
enemy = plt.Circle((10, -10), 0.75, fc='r')
agent = plt.Circle((10, -10), 0.75, fc='b')
def init():
#enemy.center = (5, 5)
#agent.center = (5, 5)
ax.add_patch(agent)
ax.add_patch(enemy)
return []
def animationManage(i,agent,enemy):
patches = []
enemy.center = (5, 5)
agent.center = (5, 5)
enemy_patches = animateCos(i,agent)
agent_patches = animateLine(i,enemy)
patches[enemy_patches, agent_patches]
#patches.append(ax.add_patch(enemy_patches))
#patches.append(ax.add_patch(agent_patches))
return enemy_patches
def animateCirc(i, patch):
# It seems that i represents time step
x, y = patch.center
# 1st constant = position and 2nd constant = trajectory
x = 50 + 30 * np.sin(np.radians(i))
y = 50 + 30 * np.cos(np.radians(i))
patch.center = (x, y)
return patch,
def animateLine(i, patch):
x, y = patch.center
x = x + 1
y = x+ 1
patch.center = (x, y)
return patch,
def animateCos(i, patch):
x, y = patch.center
x = x + 0.2
y = 50 + 30 * np.cos(np.radians(i))
patch.center = (x, y)
return patch,
def animateSin(i, patch):
x, y = patch.center
x = x + 0.2
y = 50 + 30 * np.sin(np.radians(i))
patch.center = (x, y)
return patch,
anim = animation.FuncAnimation(fig, animationManage,
init_func=init,
frames=360,
fargs=(agent,enemy,),
interval=20,
blit=True)
plt.show()
Working code for animating one particle
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(5, 4.5)
ax = plt.axes(xlim=(0, 100), ylim=(0, 100))
enemy = plt.Circle((10, -10), 0.75, fc='r')
agent = plt.Circle((10, -10), 0.75, fc='b')
def init():
enemy.center = (5, 5)
agent.center = (5, 5)
ax.add_patch(enemy)
ax.add_patch(agent)
return enemy,
def animateCirc(i, patch):
# It seems that i represents time step
x, y = patch.center
# 1st constant = position and 2nd constant = trajectory
x = 50 + 30 * np.sin(np.radians(i))
y = 50 + 30 * np.cos(np.radians(i))
patch.center = (x, y)
return patch,
def animateLine(i, patch):
x, y = patch.center
x = x + 1
y = x+ 1
patch.center = (x, y)
return patch,
def animateCos(i, patch):
x, y = patch.center
x = x + 0.2
y = 50 + 30 * np.cos(np.radians(i))
patch.center = (x, y)
return patch,
def animateSin(i, patch):
x, y = patch.center
x = x + 0.2
y = 50 + 30 * np.sin(np.radians(i))
patch.center = (x, y)
return patch,
anim = animation.FuncAnimation(fig, animateCos,
init_func=init,
frames=360,
fargs=(enemy,),
interval=20,
blit=True)
plt.show()
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(5, 4.5)
ax = plt.axes(xlim=(0, 100), ylim=(0, 100))
enemy = plt.Circle((10, -10), 0.75, fc='r')
agent = plt.Circle((10, -10), 0.75, fc='b')
def init():
enemy.center = (5, 5)
agent.center = (5, 5)
ax.add_patch(agent)
ax.add_patch(enemy)
return []
def animationManage(i,agent,enemy):
animateCos(i,enemy)
animateLine(i,agent)
return []
def animateLine(i, patch):
x, y = patch.center
x += 0.25
y += 0.25
patch.center = (x, y)
return patch,
def animateCos(i, patch):
x, y = patch.center
x += 0.2
y = 50 + 30 * np.cos(np.radians(i))
patch.center = (x, y)
return patch,
anim = animation.FuncAnimation(fig, animationManage,
init_func=init,
frames=360,
fargs=(agent,enemy,),
interval=20,
blit=True,
repeat=True)
plt.show()