I am trying to make an "animated" matplotlib line graph, with two lines which dynamically tracks the amount of UDP and TCP packets received. This is my first time doing this, and I'm using the recommend example: https://matplotlib.org/examples/animation/simple_anim.html
import pyshark
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
cap = pyshark.LiveCapture(interface="Wifi")
def sniffPackets():
tcpCount = 0
udpCount = 0
for packet in cap.sniff_continuously(packet_count=2):
print(packet)
if 'TCP' in packet:
tcpCount+=1
if 'UDP' in packet:
udpCount+=1
return tcpCount,udpCount
tcpCount,udpCount = sniffPackets()
fig, ax = plt.subplots()
tcpLine =ax.plot(tcpCount)
udpLine = ax.plot(udpCount)
def init():
tcpLine.set_ydata(0,0)
udpLine.set_ydata(0,0)
def animate():
tcpCount, udpCount = sniffPackets()
tcpLine.set_ydata(tcpCount)
udpLine.set_ydata(udpCount)
ani = animation.FuncAnimation(fig,animate,np.arange(1,200),init_func=init,interval=25,blit=True)
plt.show()
In the init function, I want both lines to start at 0, as at the beginning, the line starts at 0.
I receive this error:
AttributeError: 'list' object has no attribute 'set_ydata'
at the line:
tcpLine.set_ydata(0,0)
I'm unsure why tcpLine is being trated as a list as I defined it as tcpLine =ax.plot(tcpCount)
As per the documentation for plot(), it returns a list of Line2D object. If you are only plotting one line at a time, you can unpack the list using (notice the comma):
tcpLine, = ax.plot(tcpCount)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With