how create an animation - python

i'm a beginner in python, i really don't know how create an animation. I have different plots and i want to create a short video that concatenate these plots.
import pandas as pd
import matplotlib.pyplot as plt
data=[[1,1,3],[1,2,1],[2,1,9],[2,2,0]]
a=pd.DataFrame(data)
a.columns=['x','y','value']
data2=[[1,1,5],[1,2,2],[2,1,1],[2,2,3]]
b=pd.DataFrame(data2)
b.columns=['x','y','value']
data3=[[1,1,15],[1,2,7],[2,1,4],[2,2,8]]
c=pd.DataFrame(data3)
c.columns=['x','y','value']
final=[a,b,c]
for i in range(0,len(final)):
fig, ax = plt.subplots()
plt.scatter(final[i]['x'],final[i]['y'],c=final[i]['value'],vmin=0, vmax=15,)
plt.colorbar()

Python isn't really the way to go for creating a video.
If you want to present your graph(s) in video format, screenshot them using Windows Button + Print Screen (PrtSc) on your keyboard. This will save a screenshot to your pictures folder. Then, use a video editor, such as Vegas or free options like WeVideo to put the screenshots into a video.
You can also use presentation software, like Prezi, for a more engaging experience.

Related

How to copy an image using a URL and paste into Excel (through xlwings) without first downloading the image?

Apologies if this has been asked somewhere before, but I couldn't find a good answer. I'm trying to take an image URL obtained from scraping a website and use it to paste the image into an Excel worksheet without saving the image somewhere first. I guess this would be equivalent to right-clicking the image, copying, then pasting into Excel if someone were to try this manually.
Right now, I'm using skimage to get the image to pop up:
from skimage import io
io.imshow(io.imread('urlhere.com'))
io.show()
However, I don't think there is a way to work with the image like this and paste it into Excel using xlwings. I've seen people mention things like urllib.request.urlretrieve and PIL but these only seem to work if I want to save the image somewhere first and then bring it into Excel.
I feel like I'm missing some kind of obvious answer, but is there a way to skip the saving part and just copy the image from its URL to put it somewhere else?
Thanks!
After much trial and error, I was able to figure this out so I thought I'd post the answer:
xlwings only allows for pictures from a filepath or matplotlib figures to be added to Excel files. Therefore, I had to create a matplotlib figure of the image, turn its axes off, and insert it into the Excel file. There may be a better way to do it, but this is what worked for me:
from matplotlib import pyplot as plt
from skimage import io
import xlwings as xw
image_url = 'urlname.com'
fig = plt.figure()
plt.axis('off')
plt.imshow(io.imread(image_url))
wb = xw.Book(r'file\path\document.xlsm')
dashboard = wb.sheets['sheet1']
dashboard.pictures.add(fig)

How to play GIF in python

Thanks for help me in advance
I have a gif file say sample.gif what I want to show this GIF file in my .ipynb or without opening new window, I have series of .gif file and I am creating subplots to display gif's and can't find better solution
I see pyglet but it opens new window to display gif. As I have GIF files only so I think there is no code for provide here
Thanks for helping
EDIT : Trying below code gives error : TypeError: Image data of dtype <U10 cannot be converted to float
import matplotlib.pyplot as plt
plt.imshow('sample.gif', cmap='gray')
I found a way to do this using Ipython.display.Image but it do not plots in a subplot it shows all gif one after other in vertical. Can anyone help me on how to apply subplots on Ipython.display.Image
with open('sample.gif','rb') as f:
display(Image(data=f.read(),format="png",width =150,height=150))

Excessing Maps in python matplotlib graps

I am making a Tkinter based application in python which tracks the movement of users and plot them on a graph.
now ploting the points on a graph is no biggie, but what i couldnt manage was to give the background image as a map
currently my progress for this particular feature is nothing but as follows.
import matplotlib.pylab as plt
a=[[],[]]
a[0]=[12.28384,12,23434]#100's of values extracted from some csv file
a[1]=[80.12332,80.13312]#consider a[0],a[1] as latitude,longitude respectively
plt.plot(a[0],a[1])
plt.show()
This answer explains how to embed a map in a Tkinter window and may help.
You could also look at this example that uses the GooMPy library to embed an interactive google map in a Tkinter window.

How to use Python Seaborn Visualizations in PowerPoint?

I created some figures with Seaborn in a Jupyter Notebook. I would now like to present those figures in a PowerPoint presentation.
I know that it is possible to export the figures as png and include them in the presentation. But then they would be static, and if something changes in the dataframe, the picture would be the same. Is there an option to have a dynamic figure in PowerPoint? Something like a small Jupyter Notebook you could Display in the slides?
You could try Anaconda Fusion (also the video here), which let's you use Python inside of Excel. This could possibly work since you can link figures/data elements between Excel and PowerPoint (but special restrictions might apply when the figure is created via Python rather than standard Excel). Anaconda Fusion is free to try for a couple of months.
Another solution would be to use the Jupyter Notebook to create your presentation instead of PowerPoint. Go to View -> Cell Toolbar -> Slideshowand you can choose which code cells should become slides.
A third approach would be to create an animation of the figure as the data frame changes and then include the animation (GIF or video) in PowerPoint.
The following procedures probably won't be the most elegant solution, but it will let you produce a Seaborn plot, store it as an image file, and export the same image to an open powerpoint presentation. Depending on whether you set LinkToFile to True or False, the images will or will not update when the source changes. I'm messing around with this using cells in Spyder, but it should work in a Jupyter notebook as well. Make sure that you have a folder named c:\pptSeaborn\.
Here it is:
# Some imports
import numpy as np
import seaborn as sns
import os
import matplotlib.pyplot as plt
import win32com.client
import win32api
os.chdir('C:/pptSeaborn')
# Settings for some random data
mu = 0
sigma = 1
simulation = np.random.normal(mu, sigma, 10)
# Make seaborn plot from simulated data. Save as image file.
def SeabornPlot(data, filename = 'c:\\pptSeaborn\\snsPlot.png'):
ax = sns.kdeplot(data, shade=True)
fig = ax.get_figure()
fig.savefig(filename, bbox_inches='tight', dpi = 440)
plt.close(fig)
# Import image file to active powerpoint presentation
def SeabornPPT(plotSource, linkImage):
Application = win32com.client.Dispatch("PowerPoint.Application")
Presentation = Application.Activepresentation
slidenr = Presentation.Slides.Count + 1
Base = Presentation.Slides.Add(slidenr, 12)
gph = Base.Shapes.AddPicture(FileName=plotSource,
LinkToFile=linkImage, SaveWithDocument=True,
Left=50, Top=25, Width=800, Height=500)
Presentation.slides(slidenr).select()
# Produce data, save plot as image, and export image to powerpoint
SeabornPlot(data = simulation)
SeabornPPT(plotSource = 'c:\\pptSeaborn\\snsPlot.png', linkImage = False)
Now, if you have an open powerpoint presentation and run this whole thing five times, you will get somthing like this:
If you go ahead and save this somewhere, and reopen it, it will still look the same.
Now you can set linkImage = True, and run the whole thing five times again. Depending on the random data generated, you will still get five slides with different graphs.
But NOW, if you save the presentation and reopen it, all plots will look the same because they're linked to the same image file:
The next step could be to wrap the whole thing into a function that takes filename and LinkToFile as arguments. You could also include whether or not the procedure makes a new slide each time an image is exported. I hope you find my sggestion useful. I liked your question, and I'm hoping to see a few other suggestions as well.
We now went with this approach:
You can save the figures as a .png file and insert this into Powerpoint. There is an Option when inserting it, that the Picture will be updated every time you open PowerPoint, retrivining a new version of the file from the Folder I saved it to. So when I make changes in Seaborn, a new version of the file is automatically saved as a Picture which will then be updated in PowerPoint.

Display animation outside of jupyter notebook

I want to use Jupyter notebook to host my code for a presentation, but I don't want to embed animation into the notebook. (Because it is time-consuming to embed the video.) I want to run the cells and pop up a screen as if I am running the code in the terminal.
from matplotlib.animation import FuncAnimation
from matplotlib.pyplot import plot, show, subplots, title # annotate
from IPython.display import HTML
anim = FuncAnimation(fig, update, frames=numlin, interval=100, fargs=(
d, g, lr_D, lr_G, hasFake, speed, show_sample),
init_func=init, blit=True, repeat=0)
HTML(anim.to_html5_video())
Why using the notebook? The main reason to use the notebook is that I have many different setups for an experiment. I want to use different cells to represent different configurations, and if people want to see results from a particular configuration, I can run it right away.
Time difference. The HTML function takes over a minute to generate the video I need. While in the terminal, the animation would just start. I want to prototype quickly during a meeting while the audience asks to show the results from different initial conditions.
There is also an unexpected behavior from the notebook. The video from the notebook is different from that popped up in the terminal. The video in the notebook did not erase existing frames while drawing, making the animation looks messy and cannot track the trajectory as good as its counterpart.
Animation from the notebook's output
Animation from the terminal's output
This drawing behavior is another reason why I don't want to use the notebook to display the animation.
Will the notebook needs to show other plots. I hope so, but it is not necessary. I can open another notebook for just plots if needed.
Please let me know if I do not explain it well.
Animation inside of notebook
Reading the question, I wonder if you are aware of the %matplotlib notebook backend. While it will show the animation inside the notebook, I feel that it would suit all the described needs.
%matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
a = np.random.rand(10,4)
fig, ax =plt.subplots()
ax.axis([0,1,0,1])
points1, = plt.plot([],[], ls="", marker="d", color="indigo")
points2, = plt.plot([],[], ls="", marker="o", color="crimson")
def update(i):
points1.set_data(a[i:i+2,0],a[i:i+2,1])
points2.set_data(a[i:i+2,2],a[i:i+2,3])
return points1, points2
anim = FuncAnimation(fig, update, frames=len(a)-1, repeat=True)
Note that using this kind of animation, where the data is updated with set_data is showing the same whether saved to video or shown on screen.
Hence, if it wasn't for the time it takes to replace the video, you could well use it in the initially shown way, deleting %matplotlib notebook and adding
from IPython.display import HTML
HTML(anim.to_html5_video())
If using matplotlib 2.1, you may also opt for a JavaScript animation,
from IPython.display import HTML
HTML(ani.to_jshtml())
Animation in new window
If you want to have a window appearing, you should neither use %matplotlib inline nor %matplotlib notebook, instead replace the first line in the above code by
%matplotlib tk

Categories