Saving scatterplot animations with matplotlib produces blank video file

2024/10/14 9:26:57

I am having a very similar problem to this question

but the suggested solution doesn't work for me.

I have set up an animated scatter plot using the matplotlib animation module. This works fine when it is displaying live. I would like to save it to an avi file or something similar. The code I have written to do this does not error out but the video it produces just shows a blank set of axes or a black screen. I've done several checks and the data is being run and figure updated it's just not getting saved to video...

I tried removing "animated=True" and "blit=True" as suggested in this question but that did not fix the problem.

I have placed the relevant code below but can provide more if necessary. Could anyone suggest what I should do to get this working?

def initAnimation(self):rs, cfgs = next(self.jumpingDataStreamIterator)     #self.scat = self.axAnimation.scatter(rs[0], rs[1], c=cfgs[0], marker='o')self.scat = self.axAnimation.scatter(rs[0], rs[1], c=cfgs[0], marker='o', animated=True)return self.scat,def updateAnimation(self, i):"""Update the scatter plot."""rs, cfgs = next(self.jumpingDataStreamIterator)# Set x and y data...self.scat.set_offsets(rs[:2,].transpose()) #self.scat = self.axAnimation.scatter(rs[0], rs[1], c=cfgs[0], animated=True)# Set sizes...#self.scat._sizes = 300 * abs(data[2])**1.5 + 100# Set colors..#self.scat.set_array(cfgs[0])# We need to return the updated artist for FuncAnimation to draw..# Note that it expects a sequence of artists, thus the trailing comma.matplotlib.pyplot.draw()return self.scat,def animate2d(self, steps=None, showEvery=50, size = 25):self.figAnimation, self.axAnimation = matplotlib.pyplot.subplots()self.axAnimation.set_aspect("equal")self.axAnimation.axis([-size, size, -size, size])self.jumpingDataStreamIterator = self.jumpingDataStream(showEvery)self.univeseAnimation = matplotlib.animation.FuncAnimation(self.figAnimation, self.updateAnimation, init_func=self.initAnimation,blit=True)matplotlib.pyplot.show()def animate2dVideo(self,fileName=None, steps=10000, showEvery=50, size=25):self.figAnimation, self.axAnimation = matplotlib.pyplot.subplots()self.axAnimation.set_aspect("equal")self.axAnimation.axis([-size, size, -size, size])self.Writer = matplotlib.animation.writers['ffmpeg']self.writer = self.Writer(fps=1, metadata=dict(artist='Universe Simulation'))self.jumpingDataStreamIterator = self.jumpingDataStream(showEvery)self.universeAnimation = matplotlib.animation.FuncAnimation(self.figAnimation, self.updateAnimation, scipy.arange(1, 25), init_func=self.initAnimation)self.universeAnimation.save('C:/universeAnimation.mp4', writer = self.writer)
Answer

Sorry for the delay. I have found a work around by simply saving lots of individual images and then calling ffmpeg to chain them together. This isn't ideal but gets the job done. (part of larger class)

def easyway(self, frames):##INSERT CODE TO GET xdata and ydata!for i in range(0, frames):fileName = "videoName"+"%04d.png" % imatplotlib.pyplot.scatter(xdata,ydata,c=coldata, marker='*',s=15.0, edgecolor='none')matplotlib.pyplot.savefig(self.workingDirectory+'temp/'+fileName, dpi=dpi)matplotlib.pyplot.close()   ##INSERT CODE TO UPDATE xdata and ydata!self.createVideoFile(fps)#calls FFMpeg to chain together all the picturesif cleanUp:#removes all the picture files created in the processprint "temporary picture files being removed..."self.clearDirectory()print "FINISHED"def clearDirectory(self,directoryName='temp'):files = glob.glob(self.workingDirectory+directoryName+"/*")for f in files:os.remove(f)def createVideoFile(self,fps=3):command="ffmpeg -f image2 -r %s -i %s%s" % (str(fps), self.workingDirectory+'temp/', self.universe.description)command+="%04d.png"command+=" -c:v libx264 -r 30 %s.mp4" % (self.workingDirectory+'videos/'+self.universe.description)print "Running command:"print commandp = subprocess.Popen(command, shell=True, stdout = subprocess.PIPE, stderr=subprocess.STDOUT)output = p.communicate()[0]print "output\n"+"*"*10+"\n"print outputprint "*"*10print "Video file has been written"
https://en.xdnf.cn/q/69431.html

Related Q&A

How to group near-duplicate values in a pandas dataframe?

If there are duplicate values in a DataFrame pandas already provides functions to replace or drop duplicates. In many experimental datasets on the other hand one might have near duplicates. How can one…

python looping and creating new dataframe for each value of a column

I want to create a new dataframe for each unique value of station.I tried below which gives me only last station data updated in the dataframe = tai_new.itai[station].unique() has 500 values.for i in t…

How to put more whitespace around my plots?

I have a figure that contains two subplots in two rows and one column like so:fig, (ax1, ax2) = subplots(nrows=2,ncols=1, )The two subplots are pie charts, therefore I want their axes to be square. Aft…

using ols from statsmodels.formula.api - how to remove constant term?

Im following this first example in statsmodels tutorial:http://statsmodels.sourceforge.net/devel/How do I specify not to use constant term for linear fit in ols?# Fit regression model (using the natur…

Is numerical encoding necessary for the target variable in classification?

I am using sklearn for text classification, all my features are numerical but my target variable labels are in text. I can understand the rationale behind encoding features to numerics but dont think t…

django - regex for optional url parameters

I have a view in django that can accept a number of different filter parameters, but they are all optional. If I have 6 optional filters, do I really have to write urls for every combination of the 6 …

How do I remove transparency from a histogram created using Seaborn in python?

Im creating histograms using seaborn in python and want to customize the colors. The default settings create transparent histograms, and I would like mine to be solid. How do I remove the transparency?…

Set confidence levels in seaborn kdeplot

Im completely new to seaborn, so apologies if this is a simple question, but I cannot find anywhere in the documentation a description of how the levels plotted by n_levels are controlled in kdeplot. T…

OpenCV (cv2 in Python) VideoCapture not releasing camera after deletion

I am relatively new to Python, just having learnt it over the past month or so and have hacked this together based off examples and others code I found online.I have gotten a Tkinter GUI to display the…

Paho MQTT Python Client: No exceptions thrown, just stops

I try to setup a mqtt client in python3. This is not the first time im doing this, however i came across a rather odd behaviour. When trying to call a function, which contains a bug, from one of the c…