How do I animate a circle to move horizontally? - matplotlib

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
xvalues = np.arange(4000000, 6000000+1000, 1000).tolist()
yvalues = [5000000]*2001
Acc_11 = xvalues
Acc_12 = yvalues
fig = plt.figure(figsize = (5,5))
axes = fig.add_subplot(111)
axes.set_xlim((0, 10000000))
axes.set_ylim((0, 10000000))
point, = plt.Circle((4000000, 5000000), 60000, color = "black")
def ani(coords):
point.set_data([coords[0]],[coords[1]])
return point
def frames():
for acc_11_pos, acc_12_pos in zip(Acc_11, Acc_12):
yield acc_11_pos, acc_12_pos
ani = FuncAnimation(fig, ani, frames=frames, interval=10)
plt.show()
Im getting TypeError: 'Circle' object is not iterable. What I need to do? The size of a circle must be changable and related to axes, so matplotlib circle is the only option (I guess).

Here's a possible solution (assuming you are running in a jupyter notebook cell):
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML
xvalues = np.arange(4000000, 6000000+1000, 1000).tolist()
yvalues = [5000000]*2001
Acc_11 = xvalues
Acc_12 = yvalues
fig = plt.figure(figsize = (5,5))
axes = fig.add_subplot(111)
axes.set_xlim((0, 10000000))
axes.set_ylim((0, 10000000))
point = plt.Circle((4000000, 5000000), 60000, color = "black")
def init():
point.center = (5, 5)
axes.add_patch(point)
return point,
def ani(i):
point.center = (Acc_11[i],Acc_12[i])
return point
anim = FuncAnimation(fig,
ani,
init_func=init,
frames=200, #len(Acc_11),
interval=10)
HTML(anim.to_html5_video())
You may want to change frames=200 to frames=len(Acc_11) but it will take a while to run.

Related

Why does this plot not update ? (matplotlib)

Code below, I want to write a code that updates its function by cearing the axes and assigning new plots. It works when I only have one plot, but doesnt when I use subplots()...
Thanks
import numpy as np
import matplotlib.pyplot as plt
import time
fig , ax = plt.subplots(1,2)
x = np.linspace(0,10,10)
alpha = 0.70
def sin(x):
return np.sin(alpha*x)
def lin(x):
return alpha*x
for i in range(5):
ax[0].clear()
ax[1].clear()
ax[0].plot(x,lin(x), marker='o', label = str(i))
ax[1].plot(x,sin(x), marker='o')
fig.legend()
plt.show()
alpha = alpha**2
time.sleep(0.5)

Matplotlib clearing the figure/axis for new plot

am trying to figure out how to clear the axis in readiness for new plotting, I have tried ax.clf(), fig.clf() but nothing is happening. where am I not doing well? at the moment am not getting any errors and am using Matplotlib vers. 3.4.3.
from tkinter import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime
import mysql.connector
import matplotlib.dates as mdates
my_connect = mysql.connector.connect(host="localhost", user="Kennedy", passwd="Kennerdol05071994", database="ecg_db", auth_plugin="mysql_native_password")
mycursor = my_connect.cursor()
voltage_container = []
time_container = []
def analyze_voltage_time():
global ax, fig
pat_id = 1
query = "SELECT voltage, time FROM ecg_data_tbl where patient_id = " +str(pat_id)
mycursor.execute(query)
result = mycursor .fetchall()
voltage, time = list(zip(*result))
for volts in voltage:
voltage_container.append(volts)
for tim in time:
time_container.append(str(tim))
fig = plt.figure(1, figsize = (15, 6), dpi = 80, constrained_layout = True)
ax = fig.add_subplot()
ax.plot(time_container, voltage_container)
for label in ax.get_xticklabels():
label.set_rotation(40)
label.set_horizontalalignment('right')
ax.set_title("Electrocadiogram")
ax.set_xlabel("Time(hh:mm:ss)")
ax.set_ylabel("Voltage(mV)")
ax.grid(b=True, which='major', color='#666666', linestyle='-')
ax.minorticks_on()
ax.grid(b=True, which='minor', color='#666666', linestyle='-', alpha=0.2)
plt.show()
def clear_():
ax.cla()
fig.clf()
# =================================MAIN GUI WINDOW======================================
analysis_window = Tk()
analysis_window.configure(background='light blue')
analysis_window.iconbitmap('lardmon_icon.ico')
analysis_window.title("ECG-LArdmon - ANALYZER")
analysis_window.geometry('400x200')
analysis_window.resizable(width=False, height=False)
# ===========================BUTTONS===================================
analyse_btn = Button(analysis_window, text='analyze', width = 20, command=analyze_voltage_time)
analyse_btn.pack()
clear_btn = Button(analysis_window, text= 'clear', width = 20, command=clear_)
clear_btn.pack()
analysis_window.mainloop()

Matplotlib line chart animation

I am trying to animate a simple line chart with 2 equal arrays. I've seen some guides online but honestly, I'm not sure what I'm doing here, am I close to the solution?
I'm looking for this: https://miro.medium.com/max/1126/1*j0LxVQPbwtQDpL17TH9gZw.gif
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
x = np.array([1,2,3,4,5,6,7,8])
y = np.array([6,9,12,42,50,62,76,82])
fig = plt.figure()
ax = plt.axes(xlim=(1, 8), ylim=(6, 82))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
line.set_ydata(x[i:])
line.set_xdata(y[i:])
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
We are changing the way the data is set up. And I changed the number of frames to 9 because the number of data is 8. In addition, I used PIL to create GIF images, so please correct it.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from IPython.display import HTML
from matplotlib.animation import PillowWriter
x = np.array([1,2,3,4,5,6,7,8])
y = np.array([6,9,12,42,50,62,76,82])
fig = plt.figure()
ax = plt.axes(xlim=(1, 8), ylim=(6, 82))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
line.set_data(x[:i],y[:i])
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=9, interval=200, blit=True)
# anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
# plt.show()
anim.save('plot_ani.gif', writer='pillow')

how can i make my figure made by matplotlib response to a mouse click event?

I read the document of matplotlib and write the following code, it supposed to capture my mouse event and move the grey line position when i clicked. I read this code in jupiter notebook online, it stop to show the coordinate of my cursor as it usually do, What's happend? Can anyone help me?
import pandas as pd
import numpy as np
import matplotlib.colors as mcol
import matplotlib.cm as cm
from scipy import stats
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import scipy.spatial as spatial
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(33500,150000,3650),
np.random.normal(41000,90000,3650),
np.random.normal(41000,120000,3650),
np.random.normal(48000,55000,3650)],
index=[1992,1993,1994,1995])
fig, ax = plt.subplots()
year_avg = df.mean(axis = 1)
year_std = df.std(axis = 1)
yerr = year_std / np.sqrt(df.shape[1]) * stats.t.ppf(1-0.05/2, df.shape[1]-1)
bars=ax.bar(range(df.shape[0]), year_avg, yerr = yerr, color = 'lightslategrey')
threshold=42000
line=plt.axhline(y = threshold, color = 'grey', alpha = 0.5)
cm1 = mcol.LinearSegmentedColormap.from_list("CmapName",["yellow", "orange", "red"])
cpick = cm.ScalarMappable(cmap=cm1)
percentages = []
cpick.set_array([])
def setColor(bars, yerr,threshold):
for bar, yerr_ in zip(bars, yerr):
low = bar.get_height() - yerr_
high = bar.get_height() + yerr_
percentage = (high-threshold)/(high-low)
if percentage>1: percentage = 1
if percentage<0: percentage=0
percentages.append(percentage)
cpick.to_rgba(percentages)
bars = ax.bar(range(df.shape[0]), year_avg, yerr = yerr, color = cpick.to_rgba(percentages))
return bars
line=plt.axhline(threshold, color = 'grey', alpha = 0.5)
setColor(bars, yerr,threshold)
plt.colorbar(cpick, orientation='horizontal')
plt.xticks(range(df.shape[0]), df.index)
fig = plt.figure()
plt.show()
def onclick(event):
print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
('double' if event.dblclick else 'single', event.button,
event.x, event.y, event.xdata, event.ydata))
line.set_ydata(event.ydata)
#plt.draw()
cid = fig.canvas.mpl_connect('button_press_event', onclick)

Embedding small plots inside subplots in matplotlib

If you want to insert a small plot inside a bigger one you can use Axes, like here.
The problem is that I don't know how to do the same inside a subplot.
I have several subplots and I would like to plot a small plot inside each subplot.
The example code would be something like this:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
for i in range(4):
ax = fig.add_subplot(2,2,i)
ax.plot(np.arange(11),np.arange(11),'b')
#b = ax.axes([0.7,0.7,0.2,0.2])
#it gives an error, AxesSubplot is not callable
#b = plt.axes([0.7,0.7,0.2,0.2])
#plt.plot(np.arange(3),np.arange(3)+11,'g')
#it plots the small plot in the selected position of the whole figure, not inside the subplot
Any ideas?
I wrote a function very similar to plt.axes. You could use it for plotting yours sub-subplots. There is an example...
import matplotlib.pyplot as plt
import numpy as np
#def add_subplot_axes(ax,rect,facecolor='w'): # matplotlib 2.0+
def add_subplot_axes(ax,rect,axisbg='w'):
fig = plt.gcf()
box = ax.get_position()
width = box.width
height = box.height
inax_position = ax.transAxes.transform(rect[0:2])
transFigure = fig.transFigure.inverted()
infig_position = transFigure.transform(inax_position)
x = infig_position[0]
y = infig_position[1]
width *= rect[2]
height *= rect[3] # <= Typo was here
#subax = fig.add_axes([x,y,width,height],facecolor=facecolor) # matplotlib 2.0+
subax = fig.add_axes([x,y,width,height],axisbg=axisbg)
x_labelsize = subax.get_xticklabels()[0].get_size()
y_labelsize = subax.get_yticklabels()[0].get_size()
x_labelsize *= rect[2]**0.5
y_labelsize *= rect[3]**0.5
subax.xaxis.set_tick_params(labelsize=x_labelsize)
subax.yaxis.set_tick_params(labelsize=y_labelsize)
return subax
def example1():
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
rect = [0.2,0.2,0.7,0.7]
ax1 = add_subplot_axes(ax,rect)
ax2 = add_subplot_axes(ax1,rect)
ax3 = add_subplot_axes(ax2,rect)
plt.show()
def example2():
fig = plt.figure(figsize=(10,10))
axes = []
subpos = [0.2,0.6,0.3,0.3]
x = np.linspace(-np.pi,np.pi)
for i in range(4):
axes.append(fig.add_subplot(2,2,i))
for axis in axes:
axis.set_xlim(-np.pi,np.pi)
axis.set_ylim(-1,3)
axis.plot(x,np.sin(x))
subax1 = add_subplot_axes(axis,subpos)
subax2 = add_subplot_axes(subax1,subpos)
subax1.plot(x,np.sin(x))
subax2.plot(x,np.sin(x))
if __name__ == '__main__':
example2()
plt.show()
You can now do this with matplotlibs inset_axes method (see docs):
from mpl_toolkits.axes_grid.inset_locator import inset_axes
inset_axes = inset_axes(parent_axes,
width="30%", # width = 30% of parent_bbox
height=1., # height : 1 inch
loc=3)
Update: As Kuti pointed out, for matplotlib version 2.1 or above, you should change the import statement to:
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
There is now also a full example showing all different options available.
From matplotlib 3.0 on, you can use matplotlib.axes.Axes.inset_axes:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2,2)
for ax in axes.flat:
ax.plot(np.arange(11),np.arange(11))
ins = ax.inset_axes([0.7,0.7,0.2,0.2])
plt.show()
The difference to mpl_toolkits.axes_grid.inset_locator.inset_axes mentionned in #jrieke's answer is that this is a lot easier to use (no extra imports etc.), but has the drawback of being slightly less flexible (no argument for padding or corner locations).
source: https://matplotlib.org/examples/pylab_examples/axes_demo.html
from mpl_toolkits.axes_grid.inset_locator import inset_axes
import matplotlib.pyplot as plt
import numpy as np
# create some data to use for the plot
dt = 0.001
t = np.arange(0.0, 10.0, dt)
r = np.exp(-t[:1000]/0.05) # impulse response
x = np.random.randn(len(t))
s = np.convolve(x, r)[:len(x)]*dt # colored noise
fig = plt.figure(figsize=(9, 4),facecolor='white')
ax = fig.add_subplot(121)
# the main axes is subplot(111) by default
plt.plot(t, s)
plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])
plt.xlabel('time (s)')
plt.ylabel('current (nA)')
plt.title('Subplot 1: \n Gaussian colored noise')
# this is an inset axes over the main axes
inset_axes = inset_axes(ax,
width="50%", # width = 30% of parent_bbox
height=1.0, # height : 1 inch
loc=1)
n, bins, patches = plt.hist(s, 400, normed=1)
#plt.title('Probability')
plt.xticks([])
plt.yticks([])
ax = fig.add_subplot(122)
# the main axes is subplot(111) by default
plt.plot(t, s)
plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])
plt.xlabel('time (s)')
plt.ylabel('current (nA)')
plt.title('Subplot 2: \n Gaussian colored noise')
plt.tight_layout()
plt.show()