'How to plot and view a live animation with Python on a remote Raspberry Pi?
Background
I have installed Raspberry Pi OS Lite on a Raspberry Pi 4 (Model B with 1 GB RAM). I am developing Python on the Pi by sshing from my desktop (e.g. ssh [email protected]). I am using the Pi to act as a hardware in the loop (HIL) simulator. I am sending data from the HIL to an embedded controller for testing software.
Animation does not display when running on remote device
Upon sending data from the HIL to the controller I would also like to plot that data in an animation using matplotlib. The following matplotlib example animation program can be run on any desktop.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True)
plt.show()
However, when inside of a remote connection, the animation is not displayed (i.e. the animation does not display when running on the Pi).
Static plot can be displayed in flask webserver
The following code is a matplotlib example on how to display a plot in a webserver. When running the following scrip on the Pi I can see the plot from my desktop by going to http://raspberrypi.local:5000.
import base64
from io import BytesIO
from flask import Flask
from matplotlib.figure import Figure
app = Flask(__name__)
@app.route("/")
def hello():
# Generate the figure **without using pyplot**.
fig = Figure()
ax = fig.subplots()
ax.plot([1, 2])
# Save it to a temporary buffer.
buf = BytesIO()
fig.savefig(buf, format="png")
# Embed the result in the html output.
data = base64.b64encode(buf.getbuffer()).decode("ascii")
return f"<img src='data:image/png;base64,{data}'/>"
if __name__ == '__main__':
app.run(debug=True, threaded=True, host='0.0.0.0')
Question
The goal is to plot an animation from a Raspberry Pi and view the animation remotely. Is there any way to combine these two actions?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
