Python : Keeping up the number of points in a live plot - python

I have been trying to create a live plot by matplotlib.
My trial code is this.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import time
from PySide import QtCore
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
N=100
def animate(j):
graph_data = open('example.txt','r').read()
lines = graph_data.split('\n')
xs=[]
ys=[]
for line in lines:
if len(line) > 1:
x,y = line.split(',')
xs.append(float(x))
ys.append(float(y))
ax.clear()
ax.plot(xs, ys)
def initFile():
fid = open('example.txt','w')
fid.write('')
fid.close()
for i in range(0,N):
fid = open('example.txt', 'a')
fid.write(str(i) + ',' + str(0) + '\n')
fid.close()
def updateFile():
global wThread
wThread = writeThread()
wThread.start()
class writeThread(QtCore.QThread):
def __init__(self, parent=None):
QtCore.QThread.__init__(self, parent)
self.exiting = False
def run(self):
i=0
while 1:
fid = open('example.txt', 'a')
fid.write(str(N+i) + ',' + str(np.sin(2*np.pi*0.05*i)) + '\n')
time.sleep(0.1)
i=i+1
fid.close()
initFile()
updateFile()
ani = animation.FuncAnimation(fig, animate, interval = 200)
plt.show()
It works well. But, the plot points are accumulated. I want to keep up the number of points in my plot as N.
How could I do that?

Simply restrict the size of your array/list to the last N points:
def animate(j):
(...)
ax.clear()
ax.plot(xs[-N:], ys[-N:])

Related

how to make lines cross in matplotlib?

I'm very early in making a simple graph to plot the temperature and humidity of a given space however, the graph plots both lines but they don't intersect instead they do something like in the image below:
here's the code:
import matplotlib.pyplot as plt
from itertools import count
from matplotlib.animation import FuncAnimation
import serial
import matplotlib as mpl
import numpy as np
x = []
line1 = []
line2 = []
serialPort = serial.Serial(port = "COM3", baudrate=115200,
bytesize=8, timeout=1, stopbits=serial.STOPBITS_ONE)
serialString = ""
index = count()
def animate(i):
if serialPort.in_waiting > 0:
serialString = serialPort.readline()
string = serialString.decode('Ascii')
line1.append(string.split(' ')[0])
line2.append(string.split(' ')[1])
x.append(next(index))
print(len(line1))
if len(line1) >= 1000:
line1.pop(0)
line2.pop(0)
x.pop(0)
plt.cla()
plt.plot(x, line1, label='Temperature')
plt.plot(x, line2, label='Humidity')
ani = FuncAnimation(plt.gcf(), animate, interval=400)
plt.tight_layout()
plt.show()

live graph with matplotlib report not defined error

I try to create a live graph with matplotlib animation. below code report error:
UnboundLocalError: local variable 'lines' referenced before assignment
lines is defined above!
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
queue = []
qSize = 20
N = 3
lines = []
xidx = list(range(0, qSize))
def init():
for i in range(qSize):
queue.append([0]*N)
for i in range(N):
xdata = []
ydata = []
line, = ax.plot(xdata, ydata,label=str(i))
lines.append([line,xdata,ydata])
ax.legend(loc=2)
plt.xticks(rotation=45, ha='right')
#plt.subplots_adjust(bottom=0.30)
plt.title('Demo')
plt.ylabel('x')
plt.ylabel('Value')
return
def tick():
arr = []
for i in range(N):
d = random.randint(i*10,i*10+5)
arr.append(d)
queue.append(arr)
lines = lines[-qSize:]
return
def animate(i):
tick()
df = pd.DataFrame(data)
ax.set_xlim(0,qSize)
ax.set_ylim(df.min().min(),df.max().max())
for i,colname in enumerate(df.columns):
line,xdata,ydata = lines[i]
xdata = xidx
ydata = df[colname]
line.set_xdata(xdata)
line.set_ydata(ydata)
plt.draw()
return
init()
ani = animation.FuncAnimation(fig, animate, fargs=(), interval=1000)
plt.show()

Matplotlib live data animation runs out of memory

I'm using a Raspberry Pi to plot live data from serial, but eventually run out of memory. I'm not sure if/how I can close the figure, but still have a live data display.
Would it be possible to create and close a new figure with every animate?
My code at the moment:
import serial
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('TkAgg') #comment out for debugging
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import gc
# Create figure for plotting
fig = plt.figure()
xs = []
ysAC = []
ysDC = []
ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
ser.flush()
# This function is called periodically from FuncAnimation
def animate(i, xs, ysAC, ysDC):
values = getValues()
wAC = values[1]
wDC = values[2]
# Add x and y to lists
xs.append(i)
ysAC.append(wAC)
ysDC.append(wDC)
# Limit x and y lists to 10 items
xs = ['T-9','T-8','T-7','T-6','T-5','T-4','T-3','T-2','T-1','Now']
ysDC = ysDC[-10:]
ysAC = ysAC[-10:]
# Draw x and y lists
axRT1.clear()
if len(ysDC) == 10:
lineAC, = axRT1.plot(xs, ysAC, 'b:', label='Mains', linewidth = 4)
lineDC, = axRT1.plot(xs, ysDC, 'g--', label='Solar', linewidth = 4)
gc.collect()
#fig.clf()
#plt.close()
def getValues():
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').rstrip()
return list(line.split(","))
# Set up plot to call animate() function periodically
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ysAC, ysDC), interval=1000, blit=False)
plt.get_current_fig_manager().full_screen_toggle()
plt.ioff()
plt.show()
plt.draw()
The crude way of clearing the plots marked below fixed it for me:
import time
import serial
import datetime as dt
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('TkAgg') #comment out for debugging
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.animation as animation
from decimal import Decimal
import pandas as pd
import numpy as np
import os.path as path
import re
import gc
import os
count = 0
# Create figure for plotting
fig = plt.figure()
fig.patch.set_facecolor('whitesmoke')
hFont = {'fontname':'sans-serif', 'weight':'bold', 'size':'12'}
xs = ['T-9','T-8','T-7','T-6','T-5','T-4','T-3','T-2','T-1','Now']
ysTemp = []
ysAC = []
ysDC = []
axRT1 = fig.add_subplot(2, 2, 1)
axRT2 = axRT1.twinx() # instantiate a second axes that shares the same x-axis
#Draw x and y lists
axRT1.clear()
axRT2.clear()
axRT1.set_ylim([0, 4])
axRT2.set_ylim([10, 70])
axRT1.set_ylabel('Power Consumption kW', **hFont)
axRT2.set_ylabel('Temperature C', **hFont)
axRT1.set_xlabel('Seconds', **hFont)
axRT1.set_title('Power Consumption and Temperature - Real Time', **hFont)
lineTemp, = axRT2.plot([], [], 'r', label='Temp', linewidth = 4)
lineAC, = axRT1.plot([], [], 'b:', label='Mains', linewidth = 4)
lineDC, = axRT1.plot([], [], 'g--', label='Solar', linewidth = 4)
fig.legend([lineAC, lineDC,lineTemp], ['Mains', 'Solar', 'Temp'], fontsize=20)
ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
ser.flush()
# This function is called periodically from FuncAnimation
def animate(i, xs, ysTemp, ysAC, ysDC):
values = getValues()
if values != 0:
temp_c = Decimal(re.search(r'\d+',values[3]).group())
if temp_c < 0: temp_c = 0
wAC = round(Decimal(re.search(r'\d+', values[1]).group())/1000, 2)
if wAC < 0.35: wAC = 0
aDC = float(re.search(r'\d+', values[2]).group()) #remove characters
vDC = float(re.search(r'\d+', values[4][:5]).group()) #remove characters
wDC = aDC * vDC
wDC = round(abs(Decimal(wDC))/1000, 2)
# Add x and y to lists
ysTemp.append(temp_c)
ysAC.append(wAC)
ysDC.append(wDC)
# Limit x and y lists to 10 items
ysTemp = ysTemp[-10:]
ysDC = ysDC[-10:]
ysAC = ysAC[-10:]
if len(ysTemp) == 10:
axRT2.lines = [] #This crude way of clearing the plots worked
axRT1.lines =[] #This crude way of clearing the plots worked
lineTemp, = axRT2.plot(xs, ysTemp, 'r', label='Temp', linewidth = 4)
lineAC, = axRT1.plot(xs, ysAC, 'b:', label='Mains', linewidth = 4)
lineDC, = axRT1.plot(xs, ysDC, 'g--', label='Solar', linewidth = 4)
def getValues():
measureList = 0
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').rstrip()
print(line)
if line.count(',') == 4:
measureList = list(line.split(","))
return measureList
# Set up plot to call animate() function periodically
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ysTemp, ysAC, ysDC), interval=1000, blit=False)
plt.get_current_fig_manager().full_screen_toggle()
plt.ioff()
plt.show()
plt.draw()

Defining a unique ID for 3d bar animations, matplotlib

I'm sorry if my title is very unclear. I am working on an animation that represents a histogram of all the numbers as it crawls through a file.
I'm trying to get a unique ID, but they're all returning the same id. Then I thought about setting a unique ID, but I'm not entirely sure how to do that. I was thinking if I could just isolate the result in the sequence to be its own bar, I could clear it and then update it.
It's really hard to imagine what's going on so here's an image:
Here is the code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
import numpy as np
import random
from collections import defaultdict
from collections import deque
import re
color = f"#{random.randrange(0x1000000):06x}"
color_border = f"#{random.randrange(0x1000000):06x}"
range = [0,1,2,3,4,5,6,7,8,9]
digit_finder = re.compile(r'(\d+)')
fig = plt.figure()
ax = fig.add_subplot(111, projection= '3d')
ax.set_xticks(range)
#def text_crawler(file, place, bptrial):
def animate(i):
global z_line
global color
global color_border
_last = _f.readlines(20)
for line in _last:
_line = line.decode("utf-8")
final = digit_finder.findall(_line)
#if not final: continue
print(final[1])
z_line.append(int(final[1]))
for z in z_line:
squared_num = createdict(str(z))
xs = list(squared_num.keys())
ys = list(squared_num.values())
#ax.clear()
ax.bar(xs, ys, zs=z ,zdir='y', color = color, alpha=0.8,
linewidth=3, edgecolor = color_border)
ax.set_yticks(z_line)
ax.set_xticks(range)
print(Axes3D.bar)
def createdict(it):
x = defaultdict(int)
for k in it:
x[k] += 1
return x
count = 10
#final = list(map(lambda x: createdict(x), nums))
with open('graph_index.txt', 'rb') as index_reader:
i_first = index_reader.readline()
if not i_first:
print('This is where you return index = 0')
index_reader.seek(-2, 2)
while index_reader.read(1) != b"\n":
index_reader.seek(-2,1)
i_last = index_reader.readline().decode("utf-8")
index = digit_finder.findall(i_last)
if not index:
print('This is also index = 0...just in case.')
else:
print(int(index[0]), 'This should be a number, in bytes, where you will continue from.')
z_line = deque([],maxlen=7)
with open('numbers.txt', 'rb') as _f:
first = _f.readline(0)
_f.seek(int(index[0]), 0)
while _f.read(1) != b"\n":
_f.seek(-2,1)
ani = animation.FuncAnimation(fig, animate, interval=10000)
print(ani)
plt.show()```

Tick labels for y axis are very long. How to truncate them in seaborn?

I am plotting "McDonald's menu" data from kaggle. I plotted nutrients with food items. But, y-tick-labels are very long. How to truncate them so they fit in properly ?
grouped = df.groupby(df["Protein"])
item = grouped["Item"].sum()
item_list = item.sort_index()
item_list = item_list[-20:]
#Sizing the image canvas
plt.figure(figsize=(8,9))
#To plot bargraph
sns.barplot(item_list.index,item_list.values)
How to correct it and would it improve size of my plot ?
One idea could be to let the text in the labels roll like a marquee.
import matplotlib.pyplot as plt
import matplotlib.text
import matplotlib.animation
class Roller():
def __init__(self):
self.texts = []
def append(self, text, **kwargs):
RollingText.assimilate(text, **kwargs)
self.texts.append(text)
def roll(self, i=0):
for text in self.texts:
text.roll()
def ticklabelroll(self, i=0):
self.roll()
ticklabels = [t.get_text() for t in self.texts]
plt.gca().set_yticklabels(ticklabels)
class RollingText(matplotlib.text.Text):
n = 10
p = 0
def __init__(self, *args, **kwargs):
self.n = kwargs.pop("n", self.n)
matplotlib.text.Text(*args, **kwargs)
self.set_myprops()
def set_myprops(self, **kwargs):
self.fulltext = kwargs.get("fulltext", self.get_text())
self.n = kwargs.get("n", self.n)
if len(self.fulltext) <=self.n:
self.showntext = self.fulltext
else:
self.showntext = self.fulltext[:self.n]
self.set_text(self.showntext)
def roll(self, by=1):
self.p += by
self.p = self.p % len(self.fulltext)
if self.p+self.n <= len(self.fulltext):
self.showntext = self.fulltext[self.p:self.p+self.n]
else:
self.showntext = self.fulltext[self.p:] + " " + \
self.fulltext[0:(self.p+self.n) % len(self.fulltext)]
self.set_text(self.showntext)
#classmethod
def assimilate(cls, instance, **kwargs):
# call RollingText.assimilate(Text, n=10, ...)
instance.__class__ = cls
instance.set_myprops(**kwargs)
if __name__ == "__main__":
import pandas as pd
import seaborn as sns
fn = r"data\nutrition-facts-for-mcdonald-s-menu\menu.csv"
df = pd.read_csv(fn)
grouped = df.groupby(df["Protein"])
item = grouped["Item"].sum()
item_list = item.sort_index()
item_list = item_list[-20:]
fig, ax = plt.subplots(figsize=(10,7.5))
plt.subplots_adjust(left=0.3)
sns.barplot(item_list.index,item_list.values, ax=ax)
# create a Roller instance
r = Roller()
# append all ticklabels to the Roller
for tl in ax.get_yticklabels():
r.append(tl, n=25)
#animate the ticklabels
ani = matplotlib.animation.FuncAnimation(fig, r.ticklabelroll,
frames=36, repeat=True, interval=300)
ani.save(__file__+".gif", writer="imagemagick")
plt.show()

Categories

Resources