{"id":15245,"date":"2021-04-27T19:19:02","date_gmt":"2021-04-27T19:19:02","guid":{"rendered":"https:\/\/www.askpython.com\/?p=15245"},"modified":"2021-04-27T19:24:54","modified_gmt":"2021-04-27T19:24:54","slug":"animated-plots","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/matplotlib\/animated-plots","title":{"rendered":"Python Plot: Create Animated Plots in Python"},"content":{"rendered":"\n<p>Till now you must have seen basic <a href=\"https:\/\/www.askpython.com\/python-modules\/matplotlib\/3-dimensional-plots-in-python\" class=\"rank-math-link\">matplotlib plots<\/a>, but the same <a href=\"https:\/\/www.askpython.com\/python-modules\/matplotlib\/python-matplotlib\" class=\"rank-math-link\">matplotlib module<\/a> can be used to have <strong>animated plots<\/strong> as well! Let&#8217;s see how to build the same!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Importing necessary modules<\/h2>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport random\nfrom itertools import count\nfrom IPython import display\n<\/pre><\/div>\n\n\n<p>The table below shows each module and their requirement:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\">Module Name<\/td><td class=\"has-text-align-center\" data-align=\"center\">Requirement<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><a href=\"https:\/\/www.askpython.com\/python-modules\/numpy\/python-numpy-module\" class=\"rank-math-link\">Numpy module<\/a><\/td><td class=\"has-text-align-center\" data-align=\"center\">Used to create a dataset for the plotting.<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><a href=\"https:\/\/www.askpython.com\/python-modules\/matplotlib\/python-matplotlib\" class=\"rank-math-link\">Matplotlib module<\/a><\/td><td class=\"has-text-align-center\" data-align=\"center\">To plot the plots required<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">matplotlib.animation<\/td><td class=\"has-text-align-center\" data-align=\"center\">To provide functionalities for the animated plots<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><a href=\"https:\/\/www.askpython.com\/python-modules\/python-random-module-generate-random-numbers-sequences\" class=\"rank-math-link\">random<\/a><\/td><td class=\"has-text-align-center\" data-align=\"center\">To generate random points for random intervals intially<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">count module<\/td><td class=\"has-text-align-center\" data-align=\"center\">To generate a series of consecutive numbers<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">display module<\/td><td class=\"has-text-align-center\" data-align=\"center\">To display the videos of the animated plots<\/td><\/tr><\/tbody><\/table><figcaption>Name and Requirement of various modules<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Creating a dataset for the animated plots in Python<\/h2>\n\n\n\n<p>To create the dataset we create two lists namely <code>x<\/code> and <code>y<\/code> , where x stores the x-coordinates and y stores the y-coordinates. <\/p>\n\n\n\n<p>Now x-coordinates are consecutive numbers. We will use the cound module that does the counting of numbers starting from <code>0<\/code> after creating a count iterator using the <code>count<\/code> function. Also to access the next number we make use of the <code>next<\/code> function. <\/p>\n\n\n\n<p>For the y-coordinates, we will be using the <code>random<\/code> module to choose any <a href=\"https:\/\/www.askpython.com\/python-modules\/python-randint-method\" class=\"rank-math-link\">random integer<\/a> between two integers. The code below implements the same which includes an <code>animate<\/code> function which does the incrementation in the values:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nx=&#x5B;]\ny=&#x5B;]\ni = count()\ndef animate(j):\n    x.append(next(i))\n    y.append(random.randint(0, 10))\n    plt.plot(x,y)\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Creating the animation object<\/h2>\n\n\n\n<p>The next step involves creating an object named <code>animation_1<\/code>. To implement the <code>animate<\/code> function on repeat after a certain intervals of time we make use of the <code>FuncAnimation<\/code> which takes a few parameters which are mentioned below:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>plt.gcf() : To take the function mentioned as the next parameter as the &#8216;current function&#8217;.<\/li><li>Function name: In this case it&#8217;s <strong>animate<\/strong>.<\/li><li>interval: Set the time after which the function is repeated. <\/li><\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nanimation_1 = animation.FuncAnimation(plt.gcf(),animate,interval=1000)\nplt.show()\n<\/pre><\/div>\n\n\n<p>If you are using <code>python IDLE<\/code> , a plot will automatically generate. But, in case you are using <code>jupyter notebook<\/code> ,<strong> even after using the <code>plt.show()<\/code> function after the code, nothing will get printed as an output. <\/strong>To avoid this one needs to covert the video formed in HTML form which is mentioned in the next section.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Coverting the animated plot to HTML video (For Jupyter Notebook users)<\/h2>\n\n\n\n<p>We first need to convert the animation created to html5 video which is done in line number <code>1<\/code> in the code shown below. The line number <code>2<\/code> creates an HTML code to display the html5 video. Lastly line number <code>3<\/code> displays the html code we generated to display the video.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nvideo_1 = animation_1.to_html5_video()\nhtml_code_1 = display.HTML(video_1)\ndisplay.display(html_code_1)\nplt.tight_layout()\nplt.show()\n<\/pre><\/div>\n\n\n<p>Later in line number <code>4<\/code> and <code>5<\/code> we can simply plot the points. The output of the code results in something which is shown below. Your plot can be different than mine as the points are generated randomly.<\/p>\n\n\n\n<figure class=\"wp-block-video aligncenter\"><video height=\"396\" style=\"aspect-ratio: 576 \/ 396;\" width=\"576\" autoplay controls src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/04\/x_vs_y_animated_plot_video.mp4\"><\/video><\/figure>\n\n\n\n<p>The picture below shows the final plot after a certain point of time.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/04\/image-3.png\" alt=\"Python animated plots\" class=\"wp-image-15293\" width=\"568\" height=\"388\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/04\/image-3.png 568w, https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/04\/image-3-300x205.png 300w\" sizes=\"auto, (max-width: 568px) 100vw, 568px\" \/><figcaption>x_vs_y_animated_plot<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Plotting an animated sin wave plot <\/h2>\n\n\n\n<p>We can plot a nice sine wave using the code below. Few changes we made are as follows:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Using double of the count value generated as x-coordinate for better plot<\/li><li>Decreasing the interval in the animation function to have a clearer visualization<\/li><\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nx1=&#x5B;]\ny1=&#x5B;]\ni1 = count()\ndef animate1(j):\n    t=next(i1)\n    x1.append(2*t)\n    y1.append(np.sin(t))\n    plt.cla()\n    plt.plot(x1,y1)\nanimation_2 = animation.FuncAnimation(plt.gcf(),animate1,interval=50)\nvideo_2 = animation_2.to_html5_video()\nhtml_code_2 = display.HTML(video_2)\ndisplay.display(html_code_2)\nplt.tight_layout()\nplt.show()\n<\/pre><\/div>\n\n\n<p>The output animated plot and the static plot after a certain interval is shown below.<\/p>\n\n\n\n<figure class=\"wp-block-video aligncenter\"><video height=\"396\" style=\"aspect-ratio: 576 \/ 396;\" width=\"576\" autoplay controls src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/04\/Sine_x_vs_y_wave.mp4\"><\/video><figcaption>Video displaying sine wave<\/figcaption><\/figure>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"568\" height=\"388\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/04\/image-4.png\" alt=\"Python animated plots sine wave\" class=\"wp-image-15301\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/04\/image-4.png 568w, https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/04\/image-4-300x205.png 300w\" sizes=\"auto, (max-width: 568px) 100vw, 568px\" \/><figcaption>Sine plot after a certain interval of time<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Plotting Both Sine and Cosine on the same animated plot<\/h2>\n\n\n\n<p>Check out the code below to view both the animated curves on the same animation. We take separate y values one for sine and one for cosine curve and plot both of them on the same animation. Also, let&#8217;s spice it up a little by using <strong>&#8216;dark_background&#8217;<\/strong>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; gutter: true; title: ; notranslate\" title=\"\">\nplt.style.use(&#039;dark_background&#039;)\nx=&#x5B;]\ny_sin=&#x5B;]\ny_cos=&#x5B;]\ni_n = count()\ndef animate_n(j):\n    t=2*next(i)\n    x.append(t)\n    y_sin.append(np.sin(t))\n    y_cos.append(np.cos(t))\n    plt.cla()\n    plt.plot(x,y_sin,label=&quot;Sine wave&quot;,color=&quot;red&quot;)\n    plt.plot(x,y_cos,label=&quot;Cosine wave&quot;,color=&quot;green&quot;)\nanimation_n = animation.FuncAnimation(plt.gcf(),animate_n,interval=500)\nvideo_n = animation_n.to_html5_video()\nhtml_code_n = display.HTML(video_n)\ndisplay.display(html_code_n)\nplt.tight_layout()\nplt.show()\n<\/pre><\/div>\n\n\n<p>The animation below is the result of the code above.<\/p>\n\n\n\n<figure class=\"wp-block-video aligncenter\"><video height=\"396\" style=\"aspect-ratio: 576 \/ 396;\" width=\"576\" autoplay controls src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/04\/Sine_n_Cosine_wave_animated.mp4\"><\/video><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Congratulations! Today you learned how to plot animated plots using the matplotlib module. Hope you enjoyed coding them on your own. Thank you for reading! Happy coding and Learning! <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Till now you must have seen basic matplotlib plots, but the same matplotlib module can be used to have animated plots as well! Let&#8217;s see how to build the same! Importing necessary modules The table below shows each module and their requirement: Module Name Requirement Numpy module Used to create a dataset for the plotting. [&hellip;]<\/p>\n","protected":false},"author":28,"featured_media":15317,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[95],"tags":[],"class_list":["post-15245","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-matplotlib"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/15245","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/28"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=15245"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/15245\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/15317"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=15245"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=15245"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=15245"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}