<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Akash Jadhav on Medium]]></title>
        <description><![CDATA[Stories by Akash Jadhav on Medium]]></description>
        <link>https://medium.com/@The_Gambitier?source=rss-94426c9cc4cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*paxjPkcuQyiPMEEW.jpg</url>
            <title>Stories by Akash Jadhav on Medium</title>
            <link>https://medium.com/@The_Gambitier?source=rss-94426c9cc4cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:39:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@The_Gambitier/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Matplotlib Essentials]]></title>
            <link>https://medium.com/@The_Gambitier/matplotlib-essentials-e376ed954201?source=rss-94426c9cc4cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e376ed954201</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Akash Jadhav]]></dc:creator>
            <pubDate>Tue, 29 Jan 2019 08:24:59 GMT</pubDate>
            <atom:updated>2019-01-29T08:24:59.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*voZCGXfzHevrWCY_gf60qA.png" /></figure><p>Matplotlib is the most popular, multi-platform data visualization library built on NumPy arrays in Python. It allows us to plot 2-D graphs to get better insights from data.</p><p>This tutorial is intended to help you clear your basic concepts and know some important terminologies in library. There are two interfaces to create your graphs which most of the beginners including myself find it very confusing. But once you are clear with it everything seems intuitive. So lets get started.</p><p>In order to get the code working in this tutorial you need to have python installed along with pip. Also we’ll be using IPython/Jupyter notebook for this tutorial. Alternatively, if you don’t have it installed or want to get follow this tutorial, you can quickly access it to my google colab notebook:</p><p><a href="https://colab.research.google.com/drive/1V-IXaJbLWBxk2IyVJJRAvB-rGvvIw15H">Google Colaboratory</a></p><p>Now lets install required dependencies and install matplotlib.</p><pre><em># installing dependencies</em><br>!pip install numpy<br>!pip install matplotlib<br>!pip install pandas</pre><p>To get started, import libraries into your namespace:</p><pre><em># importing librarires</em><br>import matplotlib as mpl<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import pandas as pd</pre><h3>Setting Styles</h3><p>We will use the `plt.style` directive to choose appropriate aesthetic styles for our figures.</p><pre># Setting Styles<br>plt.style.use(&#39;classic&#39;)</pre><pre># To list all available styles, use:<br>print(plt.style.available)<br>#output: [&#39;seaborn-bright&#39;, &#39;fast&#39;, &#39;_classic_test&#39;, &#39;classic&#39;, &#39;ggplot&#39;, &#39;seaborn&#39;, &#39;seaborn-talk&#39;, &#39;seaborn-ticks&#39;, &#39;seaborn-deep&#39;, &#39;seaborn-white&#39;, &#39;dark_background&#39;, &#39;seaborn-colorblind&#39;, &#39;seaborn-paper&#39;, &#39;fivethirtyeight&#39;, &#39;seaborn-whitegrid&#39;, &#39;seaborn-dark&#39;, &#39;Solarize_Light2&#39;, &#39;seaborn-poster&#39;, &#39;bmh&#39;, &#39;seaborn-dark-palette&#39;, &#39;tableau-colorblind10&#39;, &#39;seaborn-darkgrid&#39;, &#39;seaborn-muted&#39;, &#39;grayscale&#39;, &#39;seaborn-pastel&#39;, &#39;seaborn-notebook&#39;]</pre><h3>Plotting from an IPython/Jupyter notebook</h3><p>Plotting interactively within an IPython notebook can be done if you specify Matplotlib mode. To enable this mode, you can use the %matplotlib magic command after starting ipython:</p><ul><li>%matplotlib notebook will lead to <em>interactive</em> plots embedded within the notebook</li><li>%matplotlib inline will lead to <em>static</em> images of your plot embedded in the notebook</li></ul><p>it needs to be done only once per kernel/session</p><pre>%matplotlib inline</pre><h3>Terms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WB-lBi9VbCQxPHNjM7mXIQ.png" /></figure><h3>Figure</h3><ul><li>The whole figure. The figure keeps track of all the child Axes, a smattering of ‘special’ artists (titles, figure legends, etc), and the canvas.</li><li>A figure can have any number of Axes, but to be useful should have at least one.</li><li>The easiest way to create a new figure is with pyplot:</li></ul><pre>fig = plt.figure()  <em># an empty figure with no axes</em><br>fig, ax_lst = plt.subplots(2, 2)  <em># a figure with a 2x2 grid of Axes</em></pre><h3>Axes</h3><ul><li>The Axes contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system.</li><li>The Axes class and it’s member functions are the primary entry point to working with the OO interface.</li><li>A given figure can contain many Axes, but a given Axes object can only be in one Figure.</li><li>The Axes contains two (or three in the case of 3D) Axis objects which take care of the data limits</li><li>The data limits can also be controlled via set via the set_xlim() and set_ylim() Axes methods.</li><li>Each Axes has a title (set via set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel().</li></ul><h3>Axis</h3><ul><li>These are the number-line-like objects.</li><li>They take care of setting the graph limits and generating the ticks (the marks on the axis) and ticklabels (strings labeling the ticks).</li></ul><h3>Artist</h3><ul><li>Basically everything you can see on the figure is an artist (even the Figure, Axes, and Axis objects).</li><li>When the figure is rendered, all of the artists are drawn to the canvas.</li></ul><h3>Types of inputs to plotting functions</h3><p>All of plotting functions expect np.array or np.ma.masked_array as input. Classes that are ‘array-like’ such as pandas data objects and np.matrix may or may not work as intended. It is best to convert these to np.array objects prior to plotting.</p><pre>a = pd.DataFrame(np.random.rand(4,5), columns = list(&#39;abcde&#39;))<br>a.values</pre><pre><em>#output: array([[0.69249144, 0.14049831, 0.48518893, 0.70071801, 0.57683582],</em><br><em>#              [0.7216881 , 0.55435044, 0.68774926, 0.31180173, 0.85159178],</em><br><em>#              [0.74072171, 0.11777016, 0.26252409, 0.52488437, 0.46330762],</em><br><em>#             [0.43196313, 0.91133141, 0.83722142, 0.41598821, 0.61068865]])</em><br></pre><pre>b = np.matrix([[1,2],[3,4]])<br>np.asarray(b)</pre><pre><em>#output: array([[1, 2],</em><br><em>#              [3, 4]])</em></pre><h3>Stateful vs stateless approach</h3><p>matplotlib has dual interfaces: a convenient MATLAB-style state-based interface, and a more powerful object-oriented interface.</p><h3>1. Stateful example:</h3><ul><li>There is only ever one Figure or Axes that you’re manipulating at a given time, and you don’t need to explicitly refer to it.</li><li>The stateful interface makes its calls with `plt.plot()` and other top-level pyplot functions.</li><li>The MATLAB-style/stateful approach related tools are contained in the pyplot (plt) interface.</li><li>It is important to note that this interface is stateful: it keeps track of the “current” figure and axes, which are where all plt commands are applied.</li></ul><pre>x = np.linspace(0, 2, 100)</pre><pre>plt.plot(x, x, label=&#39;linear&#39;)<br>plt.plot(x, x**2, label=&#39;quadratic&#39;)<br>plt.plot(x, x**3, label=&#39;cubic&#39;)</pre><pre>plt.xlabel(&#39;x label&#39;)<br>plt.ylabel(&#39;y label&#39;)</pre><pre>plt.title(&quot;Simple Plot&quot;)</pre><pre>plt.legend()</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*XxkHBO48NJ7mDCloGn3_zA.png" /></figure><p>The flow of this process, at a high level, looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*F9HkabLl3LXQN_06nWQbaA.jpeg" /></figure><ul><li>Calling plt.plot() is just a convenient way to get the current Axes of the current Figure and then call its plot() method.</li><li>This is what is meant by the assertion that the stateful interface always “implicitly tracks” the plot that it wants to reference.</li><li>pyplot is home to a batch of functions that are really just wrappers around matplotlib’s object-oriented interface</li><li>Calling plt.title() gets translated into this one line: gca().set_title(s, *args, **kwargs).</li><li>Similarly, if you look at the source for top-level functions like plt.grid(), plt.legend(), and plt.ylabels(), you’ll notice that all of them follow the same structure of delegating to the current Axes with gca() and then calling some method of the current Axes.</li></ul><pre>plt.plot([0,1], [1,0])</pre><p>changing size of fig</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*cJbwfP7urqUTuT7uBtbBfg.png" /></figure><pre>plt.plot([0,1], [1,0])<br>plt.gcf().set_size_inches([10,8])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*dGbpfuBKGqd8PUTyuzsQQQ.png" /></figure><pre><em># np.linspace return evenly spaced numbers over a specified interval.</em><br>x = np.linspace(0, 10, 1000)<br>plt.plot(x, np.sin(x))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*_SdCeEb2RliRsOWUmTRqdA.png" /></figure><pre><em># another example: subplot</em><br><br><em># create the first of two panels and set current axis</em><br>plt.subplot(2, 1, 1) <em># (rows, columns, panel number)</em><br>plt.plot(x, np.sin(x))<br><br><em># create the second panel and set current axis</em><br>plt.subplot(2, 1, 2)<br>plt.plot(x, np.cos(x));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*ksIlCDOoeVBj4iudqs9yjQ.png" /></figure><h3>2. stateless (or rather object-oriented approach):</h3><ul><li>Modifying the underlying objects directly is the object-oriented approach.</li><li>thus we take the object references into variables ( fig, ax, li ).</li><li>and call plotting functions that are methods of explicit Figure and Axes objects</li></ul><p>this approach is more customizable and comes handy as graphs become more complex.</p><p>The only time that the OO approach uses pyplot, to create a Figure and Axes:</p><pre>data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br>fig = plt.figure()<br>ax = plt.axes()<br>line = ax.plot(data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*6sQtgWnAURKwAIh518zs-g.png" /></figure><p><strong>what does argument in fig.add_subplot(111) mean?</strong></p><p>These are subplot grid parameters encoded as a single integer. For example, “111” means “1x1 grid, first subplot” and “234” means “2x3 grid, 4th subplot”.</p><p>Alternative form for add_subplot(111) is add_subplot(1, 1, 1).</p><pre>fig = plt.figure()<br>ax = fig.add_subplot(111)<br>li = ax.plot([0,1], [1,0])<br>fig.set_size_inches([10, 8])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*_SdCeEb2RliRsOWUmTRqdA.png" /></figure><pre><em># First create a grid of plots</em><br><em># ax will be an array of two Axes objects</em><br>fig, ax = plt.subplots(2)<br><br><em># Call plot() method on the appropriate object</em><br>ax[0].plot(x, np.sin(x))<br>ax[1].plot(x, np.cos(x));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*ksIlCDOoeVBj4iudqs9yjQ.png" /></figure><h3>Saving Plots as images</h3><pre><em># np.linspace return evenly spaced numbers over a specified interval.</em><br>x = np.linspace(0, 10, 100)</pre><pre><em># create a plot figure</em><br>fig = plt.figure()</pre><pre>plt.plot(x, np.sin(x), &#39;-&#39;)<br>plt.plot(x, np.cos(x), &#39;--&#39;);</pre><p><strong>Saving Figures to File</strong></p><p>One nice feature of Matplotlib is the ability to save figures in a wide variety of formats. Saving a figure can be done using the savefig()command. For example, to save the previous figure as a PNG file, you can run this:</p><pre>fig.savefig(&#39;my_figure.png&#39;)</pre><p>To confirm that it contains what we think it contains, let’s use the IPython Image object to display the contents of this file:</p><pre>from IPython.display import Image<br>Image(&#39;my_figure.png&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*s9hwPxC99SANurSV4gIkBg.png" /></figure><h3>Basics</h3><p>For all Matplotlib plots, we start by creating a figure and an axes. In their simplest form, a figure and axes can be created as follows:</p><ul><li>The purpose of using plt.figure() is to create a figure object.</li><li>The whole figure is regarded as the figure object.</li><li>It is necessary to explicitly use plt.figure() when we want to tweak the size of the figure and when we want to add multiple Axes objects in a single figure.</li></ul><pre>fig = plt.figure() <em># default size</em><br>fig = plt.figure(figsize=(12,8)) <em># specific </em><br><br><em>#output: &lt;Figure size 432x288 with 0 Axes&gt;</em><br><em>#output: &lt;Figure size 864x576 with 0 Axes&gt;</em><br><br><br><em># Add an axes to the current figure and make it the current axes.</em><br>ax = plt.axes()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*5OZTFzmaYR4WfUxEdt5IDA.png" /></figure><pre>fig, ax_lst = plt.subplots(2, 2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*xplS05Gx7pOe8byujvmKng.png" /></figure><pre>#so we&#39;ll be having list of axes we just created<br><br>ax_lst<br><br>#output: array([[&lt;matplotlib.axes._subplots.AxesSubplot object at 0x7f49a2367eb8&gt;,<br>#                &lt;matplotlib.axes._subplots.AxesSubplot object at 0x7f49a231e0b8&gt;],<br>#              [&lt;matplotlib.axes._subplots.AxesSubplot object at 0x7f49a23472e8&gt;,<br>#                &lt;matplotlib.axes._subplots.AxesSubplot object at 0x7f49a22ef518&gt;]],<br>#              dtype=object)</pre><p>alternatively we can get it explicitly as follows:</p><pre>fig1, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*xplS05Gx7pOe8byujvmKng.png" /></figure><h3>plt.show() v/s plt.draw()</h3><p>we have already discussed difference between plt.plot and ax.plot.</p><h3>plt.show()</h3><p>it will display the current figure that you are working on.</p><pre>plt.plot([1,2,3],[4,5,1])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*m9-yftXSCeEkGGpxQ7TVXA.png" /></figure><pre>x1 = np.random.rand(10)<br>x2 = np.random.rand(10)<br>x3 = np.random.rand(10)<br>x4 = np.random.rand(10)<br>y1 = np.random.rand(10)<br>y2 = np.random.rand(10)<br>y3 = np.random.rand(10)<br>y4 = np.random.rand(10)<br><br>figure2, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)<br>ax1.plot(x1,y1)<br>ax2.plot(x2,y2)<br>ax3.plot(x3,y3)<br>ax4.plot(x4,y4)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*WglnZsZbiloOBH6AY5R6wQ.png" /></figure><h3>plt.draw()</h3><p>plt.draw() will re-draw the figure. The plt.draw docs state:</p><ul><li>This is used in interactive mode to update a figure that has been altered using one or more plot object method calls;</li><li>it is not needed if figure modification is done entirely with pyplot functions, if a sequence of modifications ends with a pyplot function, or if matplotlib is in non-interactive mode and the sequence of modifications ends with show() or savefig().</li></ul><p>This seems to suggest that using plt.draw() before plt.show() when not in interactive mode will be redundant the vast majority of the time. The only time you may need it is if you are doing some very strange modifications that don’t involve using pyplot functions.</p><p>Refer to the Matplotlib FAQ,<a href="https://matplotlib.org/faq/usage_faq.html#what-is-interactive-mode">”What is interactive mode?”</a> for more information.</p><h3>Common Use-cases:</h3><p><strong>Setting Labels and Title:</strong></p><pre>x=[5,8,10]<br>y=[12,16,6]<br>plt.plot(x,y)<br>plt.title(&#39;Info&#39;)<br>plt.xlabel(&#39;X axis&#39;)<br>plt.ylabel(&#39;Y axis&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*3KCCcrBzCZVyMN1SKiyimg.png" /></figure><h3>How to use style in graph</h3><pre>plt.style.use(&#39;ggplot&#39;)<br>x=[5,8,10]<br>y=[12,16,6]<br>x2=[6,9,11]<br>y2=[6,15,7]<br>plt.plot(x,y, &#39;g&#39;,label=&#39;line one&#39;,linewidth=5)<br>plt.plot(x,y,&#39;c&#39;,label=&#39;line two&#39;,linewidth=5)<br>plt.title(&#39;Epic Info&#39;)<br>plt.xlabel(&#39;X axis&#39;)<br>plt.ylabel(&#39;Y axis&#39;)<br>plt.legend()<br>plt.grid(True,color=&#39;k&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*PAg8xHPljvLkzMKlNGLHnw.png" /></figure><h3>Bar Graph</h3><pre>plt.bar([1,3,5,7,9],[5,2,7,8,2], label= &#39;Example one&#39;)<br>plt.bar([2,4,6,8,10],[8,6,2,5,6], label= &#39;Example two&#39;,color=&#39;g&#39;)<br>plt.legend()<br>plt.title(&#39;Info&#39;)<br>plt.xlabel(&#39;bar number&#39;)<br>plt.ylabel(&#39;bar height&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*Gl5GmijAK5Yx-W1nvTF2Vw.png" /></figure><h3>Histogram</h3><pre>population_ages = [22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115]<br>bins=[0,10,20,30,40,50,60,70,80,90,100, 110,120,130]<br>plt.hist(population_ages, bins, histtype=&#39;bar&#39;, rwidth=0.8)<br>plt.title(&#39;Histogram&#39;)<br>plt.xlabel(&#39;x&#39;)<br>plt.ylabel(&#39;y&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*bS9Eq49nxXaGNP4jIZE9vw.png" /></figure><h3>Scatter Plot</h3><pre>x=[1,2,3,4,5,6,7,8]<br>y=[5,2,4,2,1,4,5,2]<br>plt.scatter(x,y, label=&#39;skitscat&#39;, color=&#39;k&#39;)<br>plt.title(&#39;Scatter Plot&#39;)<br>plt.xlabel(&#39;x&#39;)<br>plt.ylabel(&#39;y&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*mkm4Ll1QZp4jlyWHxvB-1Q.png" /></figure><h3>Stack Plot</h3><pre>days=[1,2,3,4,5]<br>sleeping=[7,8,6,11,7]<br>eating=[2,3,4,3,2]<br>working=[7,8,7,2,2]<br>playing=[8,5,7,8,13]<br>plt.plot([],[],color= &#39;m&#39;, label=&#39;Sleeping&#39;, linewidth=5)<br>plt.plot([],[],color= &#39;c&#39;, label=&#39;Eating&#39;, linewidth=5)<br>plt.plot([],[],color= &#39;r&#39;, label=&#39;Working&#39;, linewidth=5)<br>plt.plot([],[],color= &#39;k&#39;, label=&#39;Playing&#39;, linewidth=5)<br>plt.stackplot(days,sleeping,eating,working,playing, colors= [&#39;m&#39;, &#39;c&#39;, &#39;r&#39;, &#39;k&#39;])<br>plt.title(&#39;Stck Plot&#39;)<br>plt.xlabel(&#39;x&#39;)<br>plt.ylabel(&#39;y&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*nKDTHcCMtqRVEN40JcBNGQ.png" /></figure><p><strong>Conclusion:</strong></p><p>First of all thank you very much for taking your time to read this article. If you liked this article, my notebook please share with others! There is lot more to explore in this library, this article is just an introduction.</p><p>If you have any queries please comment below or email me on <a href="https://gambitier.github.io/#">blog.gambitier@gmail.com</a>. You can follow me on <a href="https://github.com/gambitier">github</a> or on <a href="https://twitter.com/the_gambitier">twitter</a>. By the way, I maintain my blog at: <a href="https://gambitier.github.io/">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e376ed954201" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>