Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Animation was deleted without rendering anything #28258

Open
vivimagprime opened this issue May 18, 2024 · 1 comment
Open

[Bug]: Animation was deleted without rendering anything #28258

vivimagprime opened this issue May 18, 2024 · 1 comment
Labels
Community support Users in need of help. status: needs clarification Issues that need more information to resolve.

Comments

@vivimagprime
Copy link

Bug summary

I dont know why I am getting this error. My objective is to do real time plotting in python from arduino. Please help :)

Code for reproduction

import serial
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import csv

# Constants
SERIAL_PORT = 'COM7'
BAUD_RATE = 9600

# Initialize serial connection
ser = serial.Serial(SERIAL_PORT, BAUD_RATE)

# Initialize empty lists to store data
x_vals = []
sensorValue1_data = []

# Create a function to read and process data from Arduino
def read_and_process_data():
    line = ser.readline().decode('utf-8').strip()
    sensorValues = line.split(', ')

    x_vals.append(float(sensorValues[0]))
    sensorValue1_data.append(int(sensorValues[1]))

    # Print the received values
    print(f'Time: {sensorValues[0]}, distance: {sensorValues[1]}')

# Create a function to update the plot
def update_plot(frame):
    read_and_process_data()
    plt.cla()
    plt.plot(x_vals, sensorValue1_data, label='Sensor 1')
    plt.xlabel('Time')
    plt.ylabel('distance')
    plt.legend()

# Create a function to save data to a CSV file when the plot window is closed
def on_close(event):
    with open('arduino_data.csv', 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['Time', 'Sensor1', 'Sensor2'])
        for x, s1 in zip(x_vals, sensorValue1_data):
            writer.writerow([x, s1])

# Register the callback function for when the plot window is closed
fig, ax = plt.subplots()
fig.canvas.mpl_connect('close_event', on_close)

ani = FuncAnimation(fig, update_plot, interval=10)
plt.show()

Actual outcome

runfile('C:/Users/user/Desktop/live_plot_arduino.py', wdir='C:/Users/user/Desktop')
C:\Users\user\anaconda3\lib\site-packages\matplotlib\animation.py:973: UserWarning: Animation was deleted without rendering anything. This is most likely unintended. To prevent deletion, assign the Animation to a variable that exists for as long as you need the Animation.
warnings.warn(

Expected outcome

I should be getting a live plotting of the data. I am just measuring distance with time and I want that to be plotted.

Additional information

No response

Operating system

windows

Matplotlib Version

3.4.3

Matplotlib Backend

No response

Python version

No response

Jupyter version

No response

Installation

None

@timhoffm
Copy link
Member

Please boil down your problem to a minimal working example. We cannot test your code with a serial device.

When stripping down your code, it works:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import csv


# Initialize empty lists to store data
x_vals = []
sensorValue1_data = []

# Create a function to read and process data from Arduino
def read_and_process_data():
    xn = len(x_vals)+1
    x_vals.append(xn)
    sensorValue1_data.append(np.sin(xn))
    print("read done")


# Create a function to update the plot
def update_plot(frame):
    read_and_process_data()
    plt.cla()
    plt.plot(x_vals, sensorValue1_data, label='Sensor 1')
    plt.xlabel('Time')
    plt.ylabel('distance')
    plt.legend()

# Create a function to save data to a CSV file when the plot window is closed
def on_close(event):
    print("write, write, write")

# Register the callback function for when the plot window is closed
fig, ax = plt.subplots()
fig.canvas.mpl_connect('close_event', on_close)

ani = FuncAnimation(fig, update_plot, interval=1)
plt.show()

General hint: Note that it's faster to not clear and redraw everyting in the update function. Instead, only set_data() add additional data points and update the limits if needed. See e.g. https://matplotlib.org/devdocs/gallery/animation/animate_decay.html

@timhoffm timhoffm added status: needs clarification Issues that need more information to resolve. Community support Users in need of help. labels May 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Community support Users in need of help. status: needs clarification Issues that need more information to resolve.
Projects
None yet
Development

No branches or pull requests

2 participants