Matplotlib y axis is not ordered - python

I'm getting data from serial port and draw it with matplotlib. But there is a problem. It is that i cannot order y axis values.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from deneme_serial import serial_reader
collect = serial_reader()
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs=[]
ys=[]
def animate(i, xs, ys):
xs = collect.collector()[0]
ys = collect.collector()[1]
ax.clear()
ax.plot(xs)
ax.plot(ys)
axes=plt.gca()
plt.xticks(rotation=45, ha='right')
plt.subplots_adjust(bottom=0.30)
plt.title('TMP102 Temperature over Time')
plt.ylabel('Temperature (deg C)')
ani = animation.FuncAnimation(fig, animate, fargs=(xs,ys), interval=1000)
plt.show()
Below graph is result of above code

This happened to me following the same tutorial.
My issue was the variables coming from my instrument were strings. Therefore, there is no order. I changed my variables to float and that fixed the problem
xs.append(float(FROM_INSTRUMENT))

Related

Generating repeatedly updating graph (FuncAnimation - Matplotlib)

I am trying to write a code that will generate a graph that is being repeatedly updated and has twin axes (2 y-axis, sharing the same x-axis).
The code works well when I don't combine it with FuncAnimation, however when I try to do that I get an empty graph.
def animate(i):
data=prices(a,b,c) #function that gives a DataFrame with 2 columns and index
plt.cla()
fig=plt.figure()
ax = fig.add_subplot(111)
ax.plot(data.index, data.value1)
ax2 = ax.twinx()
ax2.plot(data.index, data.value2)
plt.gcf().autofmt_xdate()
plt.tight_layout()
call = FuncAnimation(plt.gcf(), animate, 1000)
plt.tight_layout()
plt.show
'''
I believe the error is in "call". Unfortunately, I don't know FuncAnimation so well.
You can try something like this:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd
from datetime import datetime, timedelta
def getPrices(i):
return pd.DataFrame(index=[datetime.now() + timedelta(hours=i) for i in range(10)], data={'value1':range(10), 'value2':[(x + i) % 5 for x in range(10)]})
def doAnimation():
fig=plt.figure()
ax = fig.add_subplot(111)
def animate(i):
#data=prices(a,b,c) #function that gives a DataFrame with 2 columns and index
data = getPrices(i)
plt.cla()
ax.plot(data.index, data.value1)
ax2 = ax.twinx()
ax2.plot(data.index, data.value2)
plt.gcf().autofmt_xdate()
plt.tight_layout()
return ax, ax2
call = FuncAnimation(plt.gcf(), animate, 1000)
plt.show()
doAnimation()
UPDATE:
Though this works in my environment, OP in a comment indicated it doesn't work and the following warning is raised:
UserWarning: Animation was deleted without rendering anything. This is most likely not intended. To prevent deletion, assign the Animation to a variable, e.g. anim, that exists until you have outputted the Animation using plt.show() or anim.save()
As plt.show() is called immediately after the call to FuncAnimation(), this is puzzling, but perhaps the following will help to ensure the Animation does not get deleted prematurely:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd
from datetime import datetime, timedelta
def getPrices(i):
return pd.DataFrame(index=[datetime.now() + timedelta(hours=i) for i in range(10)], data={'value1':range(10), 'value2':[(x + i) % 5 for x in range(10)]})
def doAnimation():
fig=plt.figure()
ax = fig.add_subplot(111)
def animate(i):
#data=prices(a,b,c) #function that gives a DataFrame with 2 columns and index
data = getPrices(i)
plt.cla()
ax.plot(data.index, data.value1)
ax2 = ax.twinx()
ax2.plot(data.index, data.value2)
plt.gcf().autofmt_xdate()
plt.tight_layout()
return ax, ax2
call = FuncAnimation(plt.gcf(), animate, 1000)
return call
callSave = doAnimation()
plt.show()

Matplotlib not animating azimuth unless I click on the plot

I am trying to animate the point of view of a scatter plot, that is coming from a sequence of data arrays. I am currently stuck because the animation runs only if I keep clicking on the plot. It seems to animate in the background with correct timing but only displaying when I click on it.
I tried other animation examples and they were ok, so I guess there must be some problem with my code. Thanks for the help.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
data = [np.random.random_sample((300, 3)) for _ in range(10)]
x, y, z = data[0][:, 0], data[0][:, 1], data[0][:, 2]
def update_pov(num):
ax.view_init(elev=10., azim=num % 360)
return graph,
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111, projection="3d")
graph = ax.scatter(x, y, z, color='orange')
ax.set_xlim3d(0, 1)
ax.set_ylim3d(0, 1)
ax.set_zlim3d(0, 1)
ani = animation.FuncAnimation(fig, update_pov, frames=200, interval=50, blit=False)
plt.show()

Matplotlib animate plot - Figure not responding until loop is done

I am trying to animate a plot where my two vectors X,Y are updating through a loop.
I am using FuncAnimation. The problem I am running into is the Figure would show Not Responding or Blank until the loop is completed.
So during the loop, I would get something like:
But if I stopped the loop or at the end, the figure would appear.
I have set my graphics backend to automatic.
Here is the example of the code:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def animate( intermediate_values):
x = [i for i in range(len(intermediate_values))]
y = intermediate_values
plt.cla()
plt.plot(x,y, label = '...')
plt.legend(loc = 'upper left')
plt.tight_layout()
x = []
y = []
#plt.ion()
for i in range(50):
x.append(i)
y.append(i)
ani = FuncAnimation(plt.gcf(), animate(y), interval = 50)
plt.tight_layout()
#plt.ioff()
plt.show()
The structure of animation in matplotlib is that the animation function is not used in the loop process, but the animation function is the loop process. After setting up the initial graph, the animation function will update the data.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
x = []
y = []
fig = plt.figure()
ax = plt.axes(xlim=(0,50), ylim=(0, 50))
line, = ax.plot([], [], 'b-', lw=3, label='...')
ax.legend(loc='upper left')
def animate(i):
x.append(i)
y.append(i)
line.set_data(x, y)
return line,
ani = FuncAnimation(fig, animate, frames=50, interval=50, repeat=False)
plt.show()

How to show only 'x' amount of values on a graph in python

I am new to python and am carrying out some little projects along side watching tutorials to enable me to learn.
I have recently been working with some APIs to collect data - I save this data in a CSV file and then open the CSV file to show the data as a graph.
I want the graph to show the data LIVE, but in doing so I only want 10 values on the screen at once, so when the 11th value is plotted, the 1st is no longer visible unless the scrolling function is used to look back at it..
I have managed to pull together the code that plots the live data from the CSV file, as well as some code that creates the graph in the desired format - but as I am quite new to python I am unsure of how I'd make them work together.. Any advice would be greatly appreciated.
Below is the code that I have created to read and plot from a CSV file:
import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
index = count()
def animate(i):
data = pd.read_csv('x.csv')
x = data['Time']
y = data['R1Temp']
y1 = data['R2Temp']
y2 = data['R3Temp']
plt.cla()
plt.plot(x, y, marker = 'o', label='Room 1 Temp')
plt.plot(x, y1, marker = 'o', label='Room 2 Temp')
plt.plot(x, y2, marker = 'o', label='Room 3 Temp')
plt.xlabel("Time")
plt.ylabel("Temperature °C")
plt.title("Live temperature of Rooms")
plt.legend(loc='upper left')
plt.tight_layout()
ani = FuncAnimation(plt.gcf(), animate, interval=1000)
plt.tight_layout()
plt.show()
Below is the code that shows the way in which I'd like the graph to format the data plots:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update(frame):
global x, y
start = x[max(frame-PAN//2, 0)]
start = x[max(frame-PAN+1, 0)]
end = start + PAN
ax.set_xlim(start, end)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, TICK))
ax.figure.canvas.draw()
line1.set_data(x[0:frame+1], y[0:frame+1])
return (line1,)
# main
NUM = 100
TICK = 1
PAN = 10
x = np.arange(start=1, stop=NUM + 1, step=1)
for i in range(NUM):
y = np.random.rand(NUM) * 100
fig, ax = plt.subplots()
ax.set_xlim(0, PAN)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, TICK))
ax.set_ylim(0, 100)
line1, = ax.plot([], [], color="r")
ani = animation.FuncAnimation(fig, update, frames=len(x), interval=1000, repeat=False)
plt.show()
I have tried many ways to merge them together, but I just cant seem to find the correct way to go about it.
Thanks in advance!!
Showing the last N time points is quite easy. Just use DataFrame.tail() to get the last N rows of your dataframe.
Note that when doing an animation, the recommended way is to create your axes and artists outside the animation code, and only update your artists' data inside the animate code.
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
l1, = ax.plot([], [], marker='o', label='Room 1 Temp')
l2, = ax.plot([], [], marker='o', label='Room 2 Temp')
l3, = ax.plot([], [], marker='o', label='Room 3 Temp')
plt.xlabel("Time")
plt.ylabel("Temperature °C")
plt.title("Live temperature of Rooms")
plt.legend(loc='upper left')
plt.tight_layout()
def animate(i, N):
data = pd.read_csv('x.csv').tail(N)
l1.set_data(data['Time'], data['R1Temp'])
l2.set_data(data['Time'], data['R2Temp'])
l3.set_data(data['Time'], data['R3Temp'])
ax.relim()
ax.autoscale_view()
return l1, l2, l3
ani = FuncAnimation(fig, animate, interval=1000, frames=None, fargs=(10,))
plt.show()

Syntax for plotting three points' movement using FuncAnimation

My code:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
def animate(i):
ax.set_data(ax.scatter(ptx1, pty1, ptz1, c='red'),
ax.scatter(ptx2, pty2, ptz2, c='blue'),
ax.scatter(ptx3, pty3, ptz3, c='green'))
ani = FuncAnimation(fig, animate, frames=10, interval=200)
plt.show()
I'm trying to plot the movement of three points. Each ptx/y/z/1/2/3 is a list of floats giving the coordinates of the point. I'm just not sure how to use FuncAnimation to animate my points. Any help would be greatly appreciated!
Simple example. animate is called many times and everytime you have to use different data to see animation.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
# create some random data
ptx1 = [random.randint(0,100) for x in range(20)]
pty1 = [random.randint(0,100) for x in range(20)]
fig = plt.figure()
ax = fig.add_subplot(111)
def animate(i):
# use i-th elements from data
ax.scatter(ptx1[:i], pty1[:i], c='red')
# or add only one element from list
#ax.scatter(ptx1[i], pty1[i], c='red')
ani = FuncAnimation(fig, animate, frames=20, interval=500)
plt.show()

Categories