Reputation: 38
import sqlite3
import matplotlib.animation as animation
import matplotlib.pyplot as plt
def animate(i):
con = sqlite3.connect('newbase1.db')
c = con.cursor()
c.execute('SELECT Cell_1_V,Cell_2_V,Cell_1_T, time_stamp FROM Measurements')
data = c.fetchall()
Cell_1_V = []
Cell_2_V = []
Cell_1_T = []
tim = []
for row in data:
Cell_1_V.append(row[0])
Cell_2_V.append(row[1])
Cell_1_T.append(row[2])
tim.append(row[3])
fig , (sb1,sb2) = plt.subplots(nrows=2,ncols= 1)
sb1.set_xlabel("TIME---->")
sb1.set_ylabel("VOLTAGE--->")
sb2.set_xlabel("TIME---->")
sb2.set_ylabel("TEMP--->")
sb1.plot(tim,Cell_1_V,label='Cell_1_V')
sb2.plot(tim, Cell_1_T, label='Cell_1_T')
sb1.legend(loc='upper right')
sb2.legend(loc='upper right')
ani = animation.FuncAnimation(plt.gcf(), animate, interval=500)
plt.tight_layout()
plt.show()
The above is the code where I am trying to animate both subplots in the same figure but all i get is an empty plot. Any help would be appreciated.
Thanks in advance.
Upvotes: 1
Views: 1778
Reputation: 35135
The basics of animation are initialization and updating data within the animation function. This is the same for a single graph and a subplot. The data has been created appropriately; the x-axis is graphed as a date.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter
time_rng = pd.date_range('2021-01-01', freq='1d', periods=100)
vol1 = np.random.randn(100)*10
vol2 = np.random.randn(100)*10
temp1 = np.random.randn(100)+30
data = pd.DataFrame({'VOLTAGE1':vol1, 'VOLTAGE2':vol2, 'TEMP':temp1,'TIME':pd.to_datetime(time_rng)})
Cell_1_V, Cell_2_V, Cell_1_T, tim = [], [], [], []
for idx,row in data.iterrows():
Cell_1_V.append(row[0])
Cell_2_V.append(row[1])
Cell_1_T.append(row[2])
tim.append(row[3])
fig , (sb1,sb2) = plt.subplots(nrows=2,ncols= 1)
sb1.set(xlim=(mdates.date2num(tim[0]),mdates.date2num(tim[-1])), ylim=(data.VOLTAGE1.min(), data.VOLTAGE1.max()))
sb2.set(xlim=(mdates.date2num(tim[0]),mdates.date2num(tim[-1])), ylim=(data.TEMP.min(), data.TEMP.max()))
fig.subplots_adjust(hspace=0.4)
sb1.set_xlabel("TIME---->")
sb1.set_ylabel("VOLTAGE--->")
sb2.set_xlabel("TIME---->")
sb2.set_ylabel("TEMP--->")
line1, = sb1.plot([], [], label='Cell_1_V', color='C0')
line2, = sb2.plot([], [], label='Cell_1_T', color='C1')
sb1.legend(loc='upper right')
sb2.legend(loc='upper right')
date_fmt = DateFormatter("%Y-%m-%d")
sb1.xaxis.set_major_formatter(date_fmt)
sb2.xaxis.set_major_formatter(date_fmt)
line = [line1, line2]
def animate(i):
line[0].set_data(mdates.date2num(tim[:i]), Cell_1_V[:i])
line[1].set_data(mdates.date2num(tim[:i]), Cell_1_T[:i])
return line
ani = FuncAnimation(fig, animate, frames=len(data), interval=200, repeat=False)
# plt.tight_layout()
plt.show()
Upvotes: 1