Combining Slider with FuncAnimation in Python causes frames to overlap in the figure

In my 3D scatter plot animation, everything runs smoothly until I introduce a slider to the figure. At that point, new frames are drawn on top of older ones, resulting in overlapping frames (see attached image). Due to my limited understanding of how FuncAnimation works, I am unable to pinpoint what exactly is causing this issue.

Below is an elaborate description of how I execute the animation:


The animation is managed within a class called MyAnim. Upon initializing the class, I first create the 3D figures by:

class MyAnim(object):
    """Animates points on 3D wireplot"""

    def __init__(self, [...]):

        [...]

        self.fig = plt.figure(figsize=(8,8))            
        self.subplot = self.fig.add_subplot(111, projection='3d')
        self.subplot._axis3don = False  

I then run the anim method of MyAnim, which initiates the animation loop:

def anim(self):
    """Sets the animation loop"""

    frames = [...]
    self.anim = animation.FuncAnimation(self.fig, self.animate3d, frames, init_func=self.init, interval=50, blit=False, repeat=False)

In the self.init function, I set up an initial dummy scatter plot with a single transparent point at zero.

def init(self):    
   """Animation initialization"""

   self.subplot_3d_wires = self.subplot.scatter([0], [0], [0], c=RED, s=100, alpha=0)
   return [self.subplot_3d_wires]

The animation itself involves updating the position of the wire plot's grid points (next_pos) as well as drawing new positions for red (x_red, y_red, z_red) and blue (x_blue, y_blue, z_blue) scatter points on top of the wire plot.

These components of the plot are handled as follows:

def animate3d(self, i):

    plt.cla() 

    [...]

    next_pos = get_next_pos(i)

    [...]

    for j in range(X_SIZE ** 2):            

        step_l = (j) * Z_SIZE
        step_r = (j + 1) * Z_SIZE
        self.subplot_3d_wires = self.subplot.plot_wireframe(next_pos[step_l:step_r, 0], 
                                                            next_pos[step_l:step_r, 1], 
                                                            next_pos[step_l:step_r, 2], 
                                                            rstride=1, 
                                                            cstride=1, 
                                                            alpha=0.2, 
                                                            antialiased=True)

    [...]
    (x_red, y_red, z_red) = get_new_red(i)
    (x_blue, y_blue, z_blue) = get_new_blue(i)

    self.subplot_3d_wires = self.subplot.scatter(x_red, y_red, z_red, s=150, c=RED, depthshade=False, lw=0, alpha=1)
    self.subplot_3d_wires = self.subplot.scatter(x_blue, y_blue, z_blue, s=150, c=BLUE, depthshade=False, lw=0, alpha=1)

    [...]

    return [self.subplot_3d_wires]

I intend to gradually replace the animation with a slider bar (referencing a related question), so initially, I plan to add a slider using

from matplotlib.widgets import Slider
alongside my animation without any interactions between them. However, simply adding the slider causes corruption to the animation - resulting in overlaid plots as shown in the image provided.

I have attempted to instantiate the slider using:

 axcolor = 'lightgoldenrodyellow'
 axtime = plt.axes([0.25, 0.1, 0.65, 0.03])
 self.stime = Slider(axtime, 'Time', 0.0, 100.0, valinit=50.0)

both in the __init__ method of the MyAnim class and when starting the init function for the animation, but they yield the same undesirable outcome.

What steps am I overlooking here? Any assistance would be greatly appreciated!

https://i.stack.imgur.com/eIxgim.png

https://i.stack.imgur.com/uCEEOm.png

Answer №1

The issue is with the plt.cla() function. When using this command, it will clear the most recently active axes on the plot. If a slider is added, the slider's axes will be cleared instead of the plot's axes.

To solve this problem, it's important to specify which axes should be cleared by using:

self.subplot.cla()   

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Including JavaScript in HTML Error 404

https://i.stack.imgur.com/aQDPG.png I am struggling to understand why this import is not functioning as expected. I have tried using script/import.js but it still fails to work. The error message I keep receiving is: 127.0.0.1 - - [09/Sep/2020 15:09:35] ...

Move the primary window to the front in PySide

The situation: Here's the deal - I've got a total of 3 windows along with 1 window manager file. The window manager kicks off the main window and you can open other windows from there. Everything seems to be going smoothly so far. However, all t ...

Unlock the secret to retrieving specific properties from a JSON object

Whenever this code is executed: import requests import json def obtain_sole_fact(): catFact = requests.get("https://catfact.ninja/fact?max_length=140") json_data = json.loads(catFact.text) return json_data['fact'] print(obtain_s ...

Tallying Columns in Python for VLOOKUPS

Just starting out with Python and trying to apply it to a minor annoyance I encounter while using VLOOKUPS in Excel. Our databases are huge, with over 15,000 lines and columns spanning up to GG. I need an easy way to determine the column number for the loo ...

Execute a function upon selection with the appJar ListBox/OptionBox widget

I am currently exploring the appJar python module and have encountered some challenges while working with its widgets, specifically ListBox and OptionBox . I am struggling to figure out how to trigger a function when an item in ListBox or OptionBox is se ...

Implementing an array of functions on an array of elements based on their positions

Imagine the scenario: def x_squared(x): result = x * x return result def twice_x(x): result = 2 * x return result def x_cubed(x): result = x * x * x return result x_values = np.array([1, 2, 3]) functions = np.array([x_squared, t ...

Utilizing un-packaged Python scripts from GitHub

I'm currently attempting to implement the code found in this repository into my project. However, it appears that this code does not exist as a package in PyPI and lacks a setup.py file, making the typical installation process with pip install git+< ...

How to effortlessly assign keys to values within a JSON object using Python

This is how my JSON data is structured: "docs": [ { "key": [ null, null, "some_name", "12345567", "test_name" ], "value": { ...

Issue with the beautiful soup 4 library

I'm feeling puzzled as this code seems to work inconsistently. It utilizes the beautiful soup module and I'm curious why it functions in certain situations but fails at other times. from bs4 import BeautifulSoup import requests import lxml import ...

The use of Sprintf in Perl versus the corresponding equivalent in Python

Recently, I encountered a situation where I needed to work with perl code. Here is an example: $abc = sprintf("%.5f", 15.4595255213733); print ($abc) // 15.45953 Now, I am curious if there is an equivalent function to sprintf in python. If not, what woul ...

Locating specific phrases within a vast text document using Python

The code below represents the program I have written: with open("WinUpdates.txt") as f: data=[] for elem in f: data.append(elem) with open("checked.txt", "w") as f: check=True for item in data: if "KB2982791" in item: ...

How can we achieve a seamless fade transition effect between images in Ionic 2?

My search for Ionic 2 animations led me to some options, but none of them quite fit what I was looking for. I have a specific animation in mind - a "fade" effect between images. For example, I have a set of 5 images and I want each image to fade into the ...

Get the page downloaded before displaying or animating the content

Is there a method to make a browser pause and wait for all the content of a page to finish downloading before displaying anything? My webpage has several CSS3 animations, but when it is first loaded, the animations appear choppy and distorted because the ...

Adding from the iteration of the past loop in Python

I am encountering a simple yet frustrating issue. Each time I read in a list of file names stored in an ascii file ("file_input.txt") and perform calculations on them, the output from the calculation ("print peak_wv, peak_flux" in the script below) keeps ...

Amazon Web Services P3 underperforms when compared to a local GPU running Keras, TensorFlow, and MobileNet model

Currently, I am fine-tuning a pre-trained MobileNet model using Keras and TensorFlow on my local computer equipped with a GTX980. To speed up the training process, I decided to set up a p3.2xlarge instance on AWS running an Amazon Deep Learning AMI based ...

How to eliminate punctuation marks and white spaces from a string without relying on regular expressions

After importing string and string.punctuation, I ran into the issue of having '…' remaining after using string.split(). Additionally, I encountered '' mysteriously appearing even after applying strip(). My understanding was that strip ...

Enhancing SCons Cache Copy Operation

Looking for a solution to modify the behavior of SCons when copying artifacts from the cache directory to using hard links. Here is what I have tried: def link_or_copy_file(class_instance, src, dst): # perform hard linking instead... SCons.Defaults. ...

Transforming a regular expression from PHP to Python code

Looking to transition this PHP code into Python: $title_regex = "/<title>(.+)<\/title>/i"; preg_match_all($title_regex, $string, $title, PREG_PATTERN_ORDER); $url_title = $title[1]; // fetch description $tags = get_meta_tags($url); // f ...

Utilizing Python's rdflib framework to incorporate triples from a list into a graph

My current task involves adding triples to a Graph using python's rdflib package. The relationships are stored in a list (a specific column within a dataframe) sampleRelations = ['similarTo', 'brotherOf', 'capitalOf'] g ...

I struggled to successfully click a button using Selenium Python, despite experimenting with various xpaths and css selectors

I'm having trouble clicking on this yellow-highlighted button using Selenium in Python The webpage I am trying to interact with is located here: I have successfully handled both the cookie consent and allow/block notifications popups. This issue oc ...