<?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 Ishank Sharma on Medium]]></title>
        <description><![CDATA[Stories by Ishank Sharma on Medium]]></description>
        <link>https://medium.com/@ishankdev?source=rss-55118ee721e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rFNEMO_foEcXrZvvVRaqbA.jpeg</url>
            <title>Stories by Ishank Sharma on Medium</title>
            <link>https://medium.com/@ishankdev?source=rss-55118ee721e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:11:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ishankdev/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[Solving the rat and the poison puzzle with an unconventional approach]]></title>
            <link>https://ishankdev.medium.com/solving-the-rat-and-the-poison-puzzle-with-an-unconventional-approach-daf37fd28720?source=rss-55118ee721e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/daf37fd28720</guid>
            <category><![CDATA[rat-and-the-poison]]></category>
            <category><![CDATA[matrix]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[higher-dimensions]]></category>
            <dc:creator><![CDATA[Ishank Sharma]]></dc:creator>
            <pubDate>Wed, 16 Dec 2020 20:06:42 GMT</pubDate>
            <atom:updated>2020-12-16T20:06:42.915Z</atom:updated>
            <content:encoded><![CDATA[<p>The puzzle goes like this:</p><blockquote>There are 1000 wine bottles. One of the bottles contains poisoned wine. A rat dies after one hour of drinking the poisoned wine. How many minimum rats are needed to figure out which bottle contains poison in hour?</blockquote><p>If you search about it anywhere on the internet, you will likely to come across the solution which is — to number bottles from 1 to 1000 and write their corresponding binary numbers on the bottle. Each rat is assigned a position in the binary numbers written on bottles. Let us take an example. Rat 1 represents the first bit in every bottle, rat 2 represents the second bit, and so on. If rat numbers 5, 7, and 9 dies, then bottle number 42 (Binary 0000101010) is poisoned.</p><p>But can we think of an alternative method?</p><h4>The alternate method</h4><p>Let&#39;s try to solve it in a different way, without bothering about minimizing the number of rats.</p><p>For this method let us reduce our problem to 100 bottles, now arrange all the bottles in a 10*10 matrix and put 10 rats along the rows and 10 rats along the column of this matrix as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZ3IZg_5xkMXWVefyvbddA.png" /></figure><p>Now make each rat drink all the bottles present in their respective rows and columns.</p><p>In the end, there will be two rats that would die because of poison? Can you guess why?</p><p>Yes, the poisoned bottle will be drunk by two rats, one through the column and the other through the row. And if we have marked the rats from 1 to 10 respectively we would get the (x,y) coordinates of the poisoned bottle. In5 the below image we see that the 5th rat in the column and the 3rd rat in a row died hence we get the coordinates of the bottle as (5,3). So the problem got solved using 20 rats!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypQIMZY3QWc51ciNfhLlmg.png" /></figure><h3>Interesting right?</h3><p>Can we further optimise our solution?</p><p>Let’s go back to our original problem with 1000 bottles if we apply the same logic we get a matrix of 100*10 which gives us 110 rats needed to find the poisoned bottle.</p><p>So here is the twist!<br>What if we think one dimension deeper? So doing that we get a 3d matrix with dimensions as 10*10*10, and thus our number of rats got reduced to just 30 for this problem😛.</p><p>Mind blown right! and this doesn’t stop here, you can go beyond 3-dimensions and construct higher dimensional matrix, which can further optimise the problem.</p><p>So in this case if we move one dimension deeper i.e a 4d matrix, we get the dimension with least sum as 10*2*5*10 which gives us 27 rats. We will always get the most optimised answer if the number of bottle’s is nth cube of the number of dimensions needed, eg for 1000 bottles the cube root is 10th which is most optimised for third dimension.</p><h3>Conclusion</h3><p>The alternate approach doesn’t give the minimum number of rats needed, and that is one of the drawback of this method, but since this method isn’t already present on the internet, I hope this blog fills up that void space on the web.</p><p>Apart from that it is interesting to note that higher dimensions can really give us an insight of solving different problems with a unique approach.<br>And I am really curious to know what other problems can be solved in a similar manner.</p><p>That ends another blog of mine. Hope you enjoyed reading it as much as I did while writing it🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daf37fd28720" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Fourth Dimension]]></title>
            <link>https://ishankdev.medium.com/understanding-the-fourth-dimension-bdda59c8234d?source=rss-55118ee721e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdda59c8234d</guid>
            <category><![CDATA[dogs]]></category>
            <category><![CDATA[existential-crises]]></category>
            <category><![CDATA[fourth-dimension]]></category>
            <category><![CDATA[universe]]></category>
            <category><![CDATA[meaning-of-life]]></category>
            <dc:creator><![CDATA[Ishank Sharma]]></dc:creator>
            <pubDate>Thu, 03 Dec 2020 16:12:37 GMT</pubDate>
            <atom:updated>2020-12-05T14:53:39.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*gdsh3clj5XTClui2Fbcshw.png" /></figure><p><strong>Disclaimer</strong>: This article can give you existential crisis, read at your own risk.</p><h4>What on earth is a fourth dimension?</h4><p>There are multiple ways of describing it, some people might say it is time and some might say it is an extension of 3d objects perpendicular to itself. Both the definitions are correct and they are just a different aspect to describe the fourth dimension. But this blog is meant to understand the spatial aspect of the fourth dimension and not time!</p><p>We live in a three-dimensional world where everything has length, width, and height. Now if I ask you if there could be a more attribute to it? What would come to your mind?</p><p>Now let us try to empathize with a person who lives in a 2-dimensional world, the only thing he can see is the length and width of an object, if you ask him the same question i.e if there could be one more attribute to the objects other than length and width, he will probably say he doesn’t know! but we being a 3-dimensional living entity can easily pull out of the 2-dimensional being along the line perpendicular to his world and make him see 3-dimensional objects.</p><p>But will it actually make him see the 3-d world? Absolutely no, because the set of eyes he has can only see 2d, so what is it that he will be going to see?</p><p>Well, he will be seeing a very strange world that is appearing and disappearing in front of his eyes. Strange right?</p><p>Let us take a small example to understand this observation.</p><p>Imaging we pass a sphere through his 2d world, the first thing the person would see will be a point, slowly that point would appear to be increasing in size and then again it will shrink back and disappear!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*Dr7cR5RgNyLjfF9qAzy-Qg.gif" /></figure><p>This would probably give the flat-lander a hard time digesting what is actually happening in his 2-dimensional world. But we as 3d beings know what’s happening.</p><p>Now let us apply the same logic in a 3-dimensional world. This time we will pass a 4d object through a 3d world, so how would it look now?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*zTNwN4YyX6znORroAw8zBg.gif" /></figure><p>Notice how the shape of the cube is changing, and we also see that the cubes are disappearing into thin air!<br>But now if we empathize with a 4d being, we know that the cubes didn’t actually disappear! but they just went out of our 3d world.</p><h4>Still didn’t understand?</h4><p>I have been through a similar situation and I know that it can be challenging to understand the complete concept. But still, let us try to watch this video to understand things a little better</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0t4aKJuKP0Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0t4aKJuKP0Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0t4aKJuKP0Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/007713d9654ba9b89af2e40d6f489d43/href">https://medium.com/media/007713d9654ba9b89af2e40d6f489d43/href</a></iframe><p>Mind-blowing right! I am sure whatever we talked about till now, made total sense.</p><h4>Want to further blow your mind?</h4><p>You can even walk past walls if you could travel across the fourth dimension! Have a look at the following video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9yW--eQaA2I%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9yW--eQaA2I&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9yW--eQaA2I%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5cf2f741f067dc923cc388d768ec229/href">https://medium.com/media/a5cf2f741f067dc923cc388d768ec229/href</a></iframe><h4>Why bother about the fourth dimension at all?</h4><p>The world we see with our 3d eyes could be just a facade of the ultimate reality and the truth. We might tell that earth is a sphere but in reality, it is just a cross-section of the actual world out there. You never really know who might be observing us across different dimensions. There are thousands of possibilities, what if this world is just a science project of a higher dimensional college student? We never really know!</p><h4>Conclusion</h4><p>It’s creepy yet interesting to think about, and the best part is that it forces us to think beyond our existence in the first place!</p><p>I don’t want to give you an existential crisis but clearly, If you compare your life with the big universe out there, you will come to know that the purpose of our life wasn’t just “ not to be eaten by a lion in the planes of Africa” and it isn’t really to get a job at FAANG (Facebook, Apple, Amazon, Netflix, Google).</p><p>It has a much more deep-rooted meaning that we fail to notice.</p><p>This ends yet another blog of mine, hopefully, I was able to explain the fourth dimension in a three-dimensional world, on a two-dimensional screen with my one-dimensional brain (😛)</p><p>Hope you enjoyed reading, thank you and have a great day!</p><p><strong>Further material to explore more:</strong></p><p><a href="https://en.wikipedia.org/wiki/Four-dimensional_space">https://en.wikipedia.org/wiki/Tesseract#:~:text=In%20geometry%2C%20the%20tesseract%20is,six%20convex%20regular%204%2Dpolytopes.</a></p><p><a href="https://interestingengineering.com/understanding-fourth-dimension-3d-perspective#:~:text=The%20fourth%20dimension%20is%20a,perpendicular%20to%20the%20third%20dimension.&amp;text=In%20order%20to%20better%20understand,are%20being%20made%20between%20each">https://interestingengineering.com/understanding-fourth-dimension-3d-perspective#:~:text=The%20fourth%20dimension%20is%20a,perpendicular%20to%20the%20third%20dimension.&amp;text=In%20order%20to%20better%20understand,are%20being%20made%20between%20each</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdda59c8234d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse a linked list about the middle node]]></title>
            <link>https://ishankdev.medium.com/reverse-a-linked-list-about-the-middle-node-42a2f715a5d3?source=rss-55118ee721e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/42a2f715a5d3</guid>
            <category><![CDATA[competitive-coding]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[engineering-placements]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Ishank Sharma]]></dc:creator>
            <pubDate>Sun, 15 Nov 2020 11:04:46 GMT</pubDate>
            <atom:updated>2020-11-27T13:15:32.280Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reverse a linkedlist about the middle node</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*wbsl9-xLCsprOIZu0nA9Lw.png" /></figure><p>Recently this question was asked in the Paytm virtual campus coding round in my college. There were three questions overall, and this was one of them.</p><p>And since the solution to this is not directly available on the internet, I hope this blog could be of some help to someone searching for it.</p><p><strong>Problem Statement</strong>: Given a LinkedList and you had to reverse it about its midpoint.</p><p>Sample Input 1</p><pre>1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6</pre><p>Sample Output 1</p><pre>3-&gt;2-&gt;1-&gt;6-&gt;5-&gt;4</pre><p>Sample Input 2</p><pre>1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7</pre><p>Sample Output 2</p><pre>3-&gt;2-&gt;1-&gt;4-&gt;7-&gt;6-&gt;5</pre><p><strong>Naive Approach: </strong><br>This approach requires two traversals of LinkedList and two stacks using which we won’t really change the links but the values present in the nodes. Also, you should notice the difference in output when the length of the LinkedList is even and odd respectively and hence they both will be handled separately.</p><p><strong>Approach: </strong>Create two empty stack, one would contain the elements of the first half and the other would contain the elements of the second half.</p><p>This gives us two stacks as [1,2,3] and [4,5,6] (in case of even nodes) and [1,2,3], [5,6,7] in case of the odd number of nodes (notice we haven’t pushed the middle node in our stack in the second case. The reason for that will be evident later on).</p><p>Once we have the two stacks ready, traverse the original LinkedList again and pop out the elements of stack1 and stack2, and swap them with the elements present in the LinkedList as we iterate over them.</p><p>For example, in our case of even nodes we have LinkedList as [1,2,3,4,5,6], we will iterate over the LinkedList and swap stack1[top] with the current value and repeat it until stack1 is empty and repeat the same process again until the stack2 is also empty. Below is the code snippet and it is recommended to do a dry run for this in order to understand this approach.</p><pre>LinkedList 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6<br>Stack1 = [1,2,3]<br>Stack2 = [4,5,6]<br># Expected Output = 3-&gt;2-&gt;1-&gt;4-&gt;7-&gt;6-&gt;5</pre><pre>def reverse(head):<br>    temp = head<br>    while(temp!=None):</pre><pre>        if stack1:<br>            temp.data = stack1.pop()<br>        elif stack2:<br>            temp.data = stack2.pop()<br>        temp = temp.next</pre><p>While doing the dry run you will also notice why this code snippet would<strong> fail </strong>in case of an odd number of nodes. We would need to skip the middle element when the number of nodes becomes odd. Below is the code snippet to handle that case separately.</p><pre>LinkedList 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7<br>Stack1 = [1,2,3]<br>Stack2 = [5,6,7]<br># Expected Output = 3-&gt;2-&gt;1-&gt;4-&gt;7-&gt;6-&gt;5</pre><pre>def reverse(head):<br>    temp = self.head<br>    count = 0<br>    while(temp!=None):<br>        count+=1<br>        if first_half:<br>            temp.data = stack_1.pop()<br>        elif second_half:<br>            temp.data = stack_2.pop()</pre><pre>        # when middle node is reached, we skip it<br>        if count == n//2:<br>            temp = temp.next<br>        temp = temp.next</pre><p>Here is the complete solution to the above approach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b903d15cd6457b83d4b51b3f24501b7/href">https://medium.com/media/0b903d15cd6457b83d4b51b3f24501b7/href</a></iframe><h4>Time and Space Complexity Analysis</h4><p>We are traversing LinkedList twice, the first time while creating the two stacks and the second time to swap the values. This gives us an overall time complexity of <strong>O(2N) ~= O(N)</strong> and<strong> </strong>space complexity of<strong> O(2*(N/2))= O(N).</strong></p><h4>Conclusion</h4><p>This is a very bad approach and if you tell this approach during your coding interviews they would probably throw you out.</p><p>Also always keep in mind that swapping operations can be computationally expensive if the data present in the nodes is large.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26ybwvTX4DTkwst6U%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26ybwvTX4DTkwst6U%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F26ybwvTX4DTkwst6U%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/d47fd7477f76e42b2c993169f3cccc2e/href">https://medium.com/media/d47fd7477f76e42b2c993169f3cccc2e/href</a></iframe><p>A better approach would be to change the links such that both the cases are handled automatically and the problem can be solved in a single traversal. I will update this blog once I figure that out😅.</p><p>I have also noticed that during the coding rounds it is very difficult to come up with a good approach in a short span of time. So it is recommended to keep practicing coding problems in a similar timed environment as if you are actually giving a test.</p><p>That’s all from my side. Have a great day. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42a2f715a5d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Visualisation for absolute beginners using seaborn]]></title>
            <link>https://medium.com/analytics-vidhya/data-visualisation-for-absolute-beginners-using-seaborn-8cd93f705efe?source=rss-55118ee721e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cd93f705efe</guid>
            <category><![CDATA[data-visualisation]]></category>
            <category><![CDATA[seaborn]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ishank Sharma]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 13:43:58 GMT</pubDate>
            <atom:updated>2020-08-18T08:18:22.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data visualization for absolute beginners using seaborn</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTPsYgd3Ao21A3sHUYe4Mg.jpeg" /></figure><p>In my <a href="https://medium.com/analytics-vidhya/data-visualization-from-absolute-beginners-using-python-part-1-3-3cb9253ac007">previous tutorial</a>, we talked about basic plots using matplotlib, now in this tutorial, we will be building more advanced forms of data plots, and to make it more interesting we will be working on a real data set! Seaborn is a <em>wonderful</em> library that has pretty good documentation so you can always refer to it whenever you feel appropriate.</p><h4>Why learn seaborn when you already know matplotlib?</h4><blockquote>If Matplotlib “tries to make easy things easy and hard things possible”, seaborn tries to make a well-defined set of hard things easy too” — Michael Waskom (Creator of Seaborn).</blockquote><p>This seaborn library is built on top of matplotlib and after finishing this tutorial you will get to know how seaborn makes the job of plotting data much easier!</p><h4>Let’s get started!</h4><h4>Installing seaborn</h4><p>To install the Python Seaborn library, you can use the following commands based on the platform you use:</p><pre>pip install seaborn</pre><pre>or</pre><pre>conda install seaborn</pre><p>In case you are not familiar with the above, you can refer to the below link and run the commands on your browser itself. I have added all the commands in it and you can modify them to test different plots.</p><p><a href="https://colab.research.google.com/drive/17KGJsSv7qiErE6YQFiSYABGF9mih2eC7?usp=sharing">Google Colaboratory</a></p><p>We will start off by learning how to visualize the <strong>distribution of data</strong>. The <em>distribution</em> of a statistical data set (or a population) is a listing or function showing all the possible values (or intervals) of the data and how often they occur. The following seaborn methods will help us plot the same.</p><ul><li><strong>distplot</strong></li><li><strong>jointplot</strong></li><li><strong>pairplot</strong></li><li><strong>rugplot</strong></li></ul><p>Let’s head to our Jupiter Notebook and get started!</p><p><strong>Import the library</strong></p><pre>import seaborn as sns<br>%matplotlib inline</pre><p>Before beginning our plot we need a data set that we can visualize through seaborn, <strong>interestingly seaborn comes with built-in data sets!</strong></p><p>Let’s load the dataset which contains the <strong>tip given for a meal</strong> in a hotel.</p><pre>tips = sns.load_dataset(&#39;tips&#39;)</pre><p><strong>Read the dataset</strong></p><pre>tips.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*wSBYabhb5XFEDtCxxFZzWA.png" /></figure><p>Looks interesting! as you see the data set contains the total amount of the bill, a tip given, the gender of the person, was he a smoker or not, day the meal was taken, time the meal was taken, and the size of the party.</p><p>Let’s go ahead and do our first plot using <strong>distplot</strong></p><pre># distplot accepts one argument as one column of the data<br>sns.distplot(tips[&#39;total_bill&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*UBr72AjyyyPa2xfHvqDKmw.png" /></figure><p>The distplot shows the distribution of a uni-variate set of observations, univariate is just a different way of saying “one variable”.</p><p>The histogram represents the distribution of total_bill on the graph, on the y-axis we have count.</p><p>These bars that you are seeing on the graph are known as <strong>bins</strong>.</p><p>Notice we have a histogram and a KDE layer, to remove the KDE layer we would pass <strong>kde = False</strong>.</p><h4><strong>Small exercise:</strong></h4><p><strong>Can you point out in the graph where the total_bill count is max?</strong></p><p>Great! if you notice it lies between 10 dollars and 20 dollars, let’s try adding some precision to our plot by adding the number of bins as 30.</p><pre>sns.distplot(tips[&#39;total_bill&#39;],kde=False,bins=30)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*pHCDFVDEwXudelZ7QtrLzQ.png" /></figure><p>If you choose a really high bin value you will get a really weird graph and you won’t be able to estimate things properly. Bin value always depends on the data set and you need to change its value accordingly.</p><h4>jointplot</h4><p>This helps to draw a plot of two variables with bivariate and univariate graphs.</p><p>It accepts three variables x variable,y variable, and the dataset. Here x and y are column names of data.</p><pre>sns.jointplot(x= &#39;total_bill&#39;,y=&#39;tip&#39;,data=tips)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*s9nrBi6cu1wX4DtzHun1SQ.png" /></figure><p>Wow! If we notice we can see that the count of tips given on a bill between 10 and 20 dollars is more as compared to the higher bill values.</p><p>Let&#39;s try to get variation in the same graph and plot a different <strong>kind.</strong></p><p>By default we have kind = ‘default’ but we can pass in kind as as <strong>‘hex’</strong> or <strong>‘reg’</strong></p><pre>sns.jointplot(x= &#39;total_bill&#39;,y=&#39;tip&#39;,data=tips,kind = &#39;hex&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*FjxqyHK0P_wV2jZKp9AMnw.png" /></figure><pre>sns.jointplot(x= &#39;total_bill&#39;,y=&#39;tip&#39;,data=tips,kind = &#39;reg&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*komhuecysCG-kigGVTHW1g.png" /></figure><p>The above plots are more suitable for regression and machine learning (more on that later)</p><p>For easiness, we will stick to <strong>scatter plot </strong>since its easiest to read and gives more insight about the data.</p><p><strong>pairplot</strong></p><p>Usage</p><pre>sns.pairplot(tips)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*PKYlkO0kIdH7QLsbYYKKAg.png" /></figure><p>The pairplot gives us a matrix and plots every column against every other column. This plot can give a lot of insights and help find pattern among the data that we have.</p><p>Notice we get a histogram when x = y.</p><p>We can pass hue as categories and it will color based on the category, the palette is used to change the color type.</p><p><strong>Small exercise to make sure you are still awake!</strong><br>Try removing palette from the below line to see what default color you get</p><pre>sns.pairplot(tips,hue=&#39;sex&#39;,palette=&#39;coolwarm&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*KvclTxNa2L7EGSx9V2I2Cw.png" /></figure><p>Adding <strong>hue</strong>= “sex” tells <strong>seaborn you</strong> want to color the data points for male and female differently.</p><p>Try passing hue = “smoker” and see if you can find whether the tip given has to do anything with being a smoker or not 😛.</p><p><strong>rugplot</strong></p><p>rugplots are actually very simple plots, they just draw a dash mark for every point on a univariate distribution. They are the building block of a KDE plot:</p><pre>sns.rugplot(tips[&#39;total_bill&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*9DZ_20SnK70TppFIXoIpiw.png" /></figure><p>This too is a distribution plot but with a simple dash mark along the distribution line. We usually don’t use this plot so I am not focusing more here.</p><p>Awesome we successfully learned the distribution graphs🎉🎉</p><p>I can’t wait to show you more advanced graphs that seaborn provides.</p><p>Let’s jump right onto it!</p><h3>Categorical Data Plots</h3><p>Now let’s plot categorical data! There are a few main plot types for this:</p><ul><li><strong>factorplot</strong></li><li><strong>boxplot</strong></li><li><strong>violinplot</strong></li><li><strong>stripplot</strong></li><li><strong>swarmplot</strong></li><li><strong>barplot</strong></li><li><strong>countplot</strong></li></ul><p>We will be seeing all of them one by one and learn to pick the right plot for the right use case.</p><pre>import seaborn as sns<br>%matplotlib inline<br>tips = sns.load_dataset(&#39;tips&#39;)<br>tips.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*U1eAkpL5v7QaGc0s3NsHrw.png" /></figure><h3>barplot and countplot</h3><p>These very similar plots allow you to get aggregate data off a categorical feature in your data. <strong>barplot</strong> is a general plot that allows you to aggregate the categorical data based on some function, by default the mean:</p><pre>import numpy as np</pre><pre>sns.barplot(x=&#39;sex&#39;,y=&#39;total_bill&#39;,data=tips)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*dclTMqrnYaFPigH3EAxa3g.png" /></figure><p>You can change the estimator object to your own function, that converts a vector to a scalar:</p><pre>import numpy as np</pre><pre>sns.barplot(x=&#39;sex&#39;,y=&#39;total_bill&#39;,data=tips,estimator=np.std)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*-7uJissQc2f4Cvz8CE39Mw.png" /></figure><p><strong>countplot</strong></p><p>This is essentially the same as barplot except the estimator is explicitly counting the number of occurrences. Which is why we only pass the x value:</p><pre>sns.countplot(x=&#39;sex&#39;,data=tips)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*jgMAZiTRd4bKxkPzQ6tkQA.png" /></figure><h3>boxplot and violinplot</h3><p><strong>boxplots</strong> and <strong>violinplots</strong> are used to show the distribution of categorical data. A box plot (or box-and-whisker plot) shows the distribution of quantitative data in a way that facilitates comparisons between variables or across levels of a categorical variable. The box shows the quartiles of the dataset while the whiskers extend to show the rest of the distribution, except for points that are determined to be “outliers” using a method that is a function of the inter-quartile range. This will be more clear when we start plotting them.</p><pre>sns.boxplot(x=&quot;day&quot;, y=&quot;total_bill&quot;, data=tips,palette=&#39;rainbow&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*NzIFqJgu7g62FQzCMgH_EQ.png" /></figure><pre># Can do entire dataframe with orient=&#39;h&#39;<br>sns.boxplot(data=tips,palette=&#39;rainbow&#39;,orient=&#39;h&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*QkWuagAAXOfuXu4TKFV2Kg.png" /></figure><pre># adding hue to the data<br>sns.boxplot(x=&quot;day&quot;, y=&quot;total_bill&quot;, hue=&quot;smoker&quot;,data=tips, palette=&quot;coolwarm&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*L7ivlz6xufhEIjZLfs0ckg.png" /></figure><p>Notice how easy it becomes to add a hue and visualise the smokers in our dataset.</p><h3>violinplot</h3><p>A violin plot plays a similar role as a box and whisker plot. It shows the distribution of quantitative data across several levels of one (or more) categorical variables such that those distributions can be compared. Unlike a box plot, in which all of the plot components correspond to actual data points, the violin plot features a kernel density estimation of the underlying distribution.</p><pre>sns.violinplot(x=&quot;day&quot;, y=&quot;total_bill&quot;, data=tips,palette=&#39;rainbow&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*z5IsO_QB6rY5i5A4rAORTQ.png" /></figure><pre># adding hue by sex<br>sns.violinplot(x=&quot;day&quot;, y=&quot;total_bill&quot;, data=tips,hue=&#39;sex&#39;,split=True,palette=&#39;Set1&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*qVHAwAyphgXHEyQNHwr42A.png" /></figure><pre>#make one half the one hue and another half the other hue using split<br>sns.violinplot(x=&quot;day&quot;, y=&quot;total_bill&quot;, data=tips,hue=&#39;sex&#39;,split=True,palette=&#39;Set1&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*gX03AmMcnSx2B6Yf0r3VQw.png" /></figure><p>Notice above how <strong>split = True </strong>gives out a lot of information and we are able to easily compare both the genders side by side.</p><h3>stripplot and swarmplot</h3><p>The stripplot will draw a scatterplot where one variable is categorical. A strip plot can be drawn on its own, but it is also a good complement to a box or violin plot in cases where you want to show all observations along with some representation of the underlying distribution.</p><pre>sns.stripplot(x=&quot;day&quot;, y=&quot;total_bill&quot;, data=tips)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*m-kZ5g0HhKGpYM28KjotHw.png" /></figure><pre>#adding will add random noise to make it clear<br>sns.stripplot(x=&quot;day&quot;, y=&quot;total_bill&quot;, data=tips,jitter=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*pMKkyS9PtlcVroF1esSEZA.png" /></figure><pre># adding hue <br>sns.stripplot(x=&quot;day&quot;, y=&quot;total_bill&quot;, data=tips,jitter=True,hue=&#39;sex&#39;,palette=&#39;Set1&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*b2oPLx062Ft-NnmBhhr55Q.png" /></figure><pre>#adding split = True<br>sns.stripplot(x=&quot;day&quot;, y=&quot;total_bill&quot;, data=tips,jitter=True,hue=&#39;sex&#39;,palette=&#39;Set1&#39;,split=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*syzCTGV0d7TlHeYazfAk5A.png" /></figure><p>The swarmplot is similar to stripplot(), but the points are adjusted (only along the categorical axis) so that they don’t overlap. This gives a better representation of the distribution of values, although it does not scale as well to large numbers of observations (both in terms of the ability to show all the points and in terms of the computation needed to arrange them).sns.swarmplot(x=&quot;day&quot;, y=&quot;total_bill&quot;, data=tips)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*OJFCcwn16DQSoT97P-DWmg.png" /></figure><pre>sns.swarmplot(x=&quot;day&quot;, y=&quot;total_bill&quot;,hue=&#39;sex&#39;,data=tips, palette=&quot;Set1&quot;, split=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*dMkWNg056xc-SaL-u5VrrQ.png" /></figure><h3>Combining Categorical Plots</h3><pre>sns.violinplot(x=&quot;tip&quot;, y=&quot;day&quot;, data=tips,palette=&#39;rainbow&#39;)<br>sns.swarmplot(x=&quot;tip&quot;, y=&quot;day&quot;, data=tips,color=&#39;black&#39;,size=3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*uNL8vFhR3ZynjItRZ_IM9w.png" /></figure><h3>factorplot</h3><p>factorplot is the most general form of a categorical plot. It can take in a <strong>kind</strong> parameter to adjust the plot type:</p><pre>sns.factorplot(x=&#39;sex&#39;,y=&#39;total_bill&#39;,data=tips,kind=&#39;bar&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*t2b3elL2ZMR-HI6VwrzybQ.png" /></figure><p>Great Job! and congratulations on making this far🎉🎉, If I had an emoji for patting you on the back I would press it a million times 🥳🥳.</p><p>However, these are just the basics there is much of what seaborn has to offer, and I am looking forward to creating more advanced tutorials for the same.</p><p>Follow me on medium to keep yourself updated for all new updates.</p><p>Thank you</p><p>Further readings</p><ul><li><a href="http://seaborn.pydata.org/tutorial.html">http://seaborn.pydata.org/tutorial.html</a></li></ul><p>Sources</p><ul><li><a href="http://seaborn.pydata.org/tutorial.html">http://seaborn.pydata.org/tutorial.html</a></li><li><a href="http://seaborn.pydata.org/examples/index.html">http://seaborn.pydata.org/examples/index.html</a></li><li><a href="https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/">https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cd93f705efe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/data-visualisation-for-absolute-beginners-using-seaborn-8cd93f705efe">Data Visualisation for absolute beginners using seaborn</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Visualization for absolute beginner [part 3/3]]]></title>
            <link>https://medium.com/analytics-vidhya/data-visualization-for-absolute-beginner-part-3-3-96a00d04497f?source=rss-55118ee721e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/96a00d04497f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[Ishank Sharma]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 19:06:12 GMT</pubDate>
            <atom:updated>2020-08-23T14:28:16.954Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Visualization for absolute beginners[part 3/3]</h3><h4>Legends, labels, and titles</h4><p>By now we have covered the basics of creating a figure canvas and add axes instances to it, Let’s now focus on how we can add titles, axis labels, and legends to our plots.</p><h4>Figure titles</h4><p>An axes contains the method set_titlewhich can be added to each axis instance in a figure.</p><pre>ax.set_title(&quot;title&quot;);</pre><p><strong>Axis labels</strong></p><p>Similarly, for setting xlabel and ylabel we use set_xlabel and set_ylabelrespectively.</p><pre>ax.set_xlabel(&quot;x&quot;)<br>ax.set_ylabel(&quot;y&quot;);</pre><h4>Legends</h4><p>We will use <strong>label = “label text”</strong> keyword when plots are added to the figure, and then we are going to call <strong>legend()</strong> method without argument for adding it to the figure.</p><pre>fig = plt.figure()</pre><pre>ax = fig.add_axes([0,0,1,1])</pre><pre>ax.plot(x, x**2, label=&quot;x**2&quot;)<br>ax.plot(x, x**3, label=&quot;x**3&quot;)<br>ax.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*nK2MqnbOqeK4qMu0RGAGag.png" /></figure><p>Observe and see how the legend overlaps some of the actual plot!</p><p>We should note that the legend function takes the optional argument <strong>loc </strong>that is used to specify where the legend will be drawn.<br>See the<a href="http://matplotlib.org/users/legend_guide.html#legend-location"> documentation</a> for more details</p><pre># We have a lot of options</pre><pre>ax.legend(loc=1) # upper right corner<br>ax.legend(loc=2) # upper left corner<br>ax.legend(loc=3) # lower left corner<br>ax.legend(loc=4) # lower right corner</pre><pre># .. many more options are available</pre><pre># Most common to choose<br>ax.legend(loc=0) # let matplotlib decide the optimal location<br>fig</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*2kfCgUs6P-LUrX26cs9oiQ.png" /></figure><h4>Setting colors, linewidths, linetypes</h4><p>Matplotlib provides us <em>a bunch </em>of options for customizing colors, linewidths, and linetypes. These are used to change how our plot looks.</p><h4>Colors with MatLab like syntax</h4><p>Using matplotlib we will now define the color of lines in multiple ways. For eg ‘g — ’ means a green dashed line.</p><pre># MATLAB style line color and style <br>fig, ax = plt.subplots()<br>ax.plot(x, x**2, &#39;b.-&#39;) # blue line with dots<br>ax.plot(x, x**3, &#39;g--&#39;) # green dashed line</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*m-ljGQpapCpgjB4vkTTiGg.png" /></figure><h4>Colors with the color= parameter</h4><p>Another way to define colors is by their RGB or HEX codes we can also provide alpha value to indicate the opacity.</p><pre>fig, ax = plt.subplots()</pre><pre>ax.plot(x, x+1, color=&quot;blue&quot;, alpha=0.5) # half-transparant<br>ax.plot(x, x+2, color=&quot;#8B008B&quot;)        # RGB hex code<br>ax.plot(x, x+3, color=&quot;#FF8C00&quot;)        # RGB hex code</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*aHpRPg-KUaVX3XEMTNScKA.png" /></figure><h4>Line and marker styles</h4><p>Changing the line width can be done using linewidth or lw keyword. The line style can be selected using ls orlinestyle keyword. Linestyle defines the line type such as dashed line or a dotted line.</p><pre>fig, ax = plt.subplots(figsize=(12,6))</pre><pre>ax.plot(x, x+1, color=&quot;red&quot;, linewidth=0.25)<br>ax.plot(x, x+2, color=&quot;red&quot;, linewidth=0.50)<br>ax.plot(x, x+3, color=&quot;red&quot;, linewidth=1.00)<br>ax.plot(x, x+4, color=&quot;red&quot;, linewidth=2.00)</pre><pre># possible linestype options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’<br>ax.plot(x, x+5, color=&quot;green&quot;, lw=3, linestyle=&#39;-&#39;)<br>ax.plot(x, x+6, color=&quot;green&quot;, lw=3, ls=&#39;-.&#39;)<br>ax.plot(x, x+7, color=&quot;green&quot;, lw=3, ls=&#39;:&#39;)</pre><pre># custom dash<br>line, = ax.plot(x, x+8, color=&quot;black&quot;, lw=1.50)<br>line.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...</pre><pre># possible marker symbols: marker = &#39;+&#39;, &#39;o&#39;, &#39;*&#39;, &#39;s&#39;, &#39;,&#39;, &#39;.&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, ...<br>ax.plot(x, x+ 9, color=&quot;blue&quot;, lw=3, ls=&#39;-&#39;, marker=&#39;+&#39;)<br>ax.plot(x, x+10, color=&quot;blue&quot;, lw=3, ls=&#39;--&#39;, marker=&#39;o&#39;)<br>ax.plot(x, x+11, color=&quot;blue&quot;, lw=3, ls=&#39;-&#39;, marker=&#39;s&#39;)<br>ax.plot(x, x+12, color=&quot;blue&quot;, lw=3, ls=&#39;--&#39;, marker=&#39;1&#39;)</pre><pre># marker size and color<br>ax.plot(x, x+13, color=&quot;purple&quot;, lw=1, ls=&#39;-&#39;, marker=&#39;o&#39;, markersize=2)<br>ax.plot(x, x+14, color=&quot;purple&quot;, lw=1, ls=&#39;-&#39;, marker=&#39;o&#39;, markersize=4)<br>ax.plot(x, x+15, color=&quot;purple&quot;, lw=1, ls=&#39;-&#39;, marker=&#39;o&#39;, markersize=8, markerfacecolor=&quot;red&quot;)<br>ax.plot(x, x+16, color=&quot;purple&quot;, lw=1, ls=&#39;-&#39;, marker=&#39;s&#39;, markersize=8,markerfacecolor=&quot;yellow&quot;, markeredgewidth=3, markeredgecolor=&quot;green&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*Q0YTl0BIYWVNW6_HlBFObg.png" /></figure><h4>Control over axis appearance</h4><p>Now we will be learning about controlling the axis sizing properties in a figure.</p><p><strong>Plot range</strong></p><p>To add ranges of the axes we can use set_ylim and set_xlim attributes to the axis object, or axis(&#39;tight&#39;) for automatically getting &quot;tightly fitted&quot; axes ranges.</p><pre>fig, axes = plt.subplots(1, 3, figsize=(12, 4))</pre><pre>axes[0].plot(x, x**2, x, x**3)<br>axes[0].set_title(&quot;default axes ranges&quot;)</pre><pre>axes[1].plot(x, x**2, x, x**3)<br>axes[1].axis(&#39;tight&#39;)<br>axes[1].set_title(&quot;tight axes&quot;)</pre><pre>axes[2].plot(x, x**2, x, x**3)<br>axes[2].set_ylim([0, 60])<br>axes[2].set_xlim([2, 5])<br>axes[2].set_title(&quot;custom axes range&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*WMipbzXd2_ywaLwXktItHw.png" /></figure><h4>Special Plot Types</h4><p>The matplotlib is not just restricted to these simple line plots, it also provides us many specialized plots that we can create such as bar plots, pie charts, scatter plots and much more.</p><p>But in my opinion it’s better to use seaborn for these special types of charts. And we will discuss about them in a different tutorial.</p><p>Before wrapping up let’s discuss a few more examples of these specialtype of plots.</p><h4><strong>Scatter Plot</strong></h4><pre>plt.scatter(x,y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*MzIxOJek0nCmcIrH2FD7TQ.png" /></figure><h4>Histogram</h4><pre>from random import sample<br>data = sample(range(1, 1000), 100)<br>plt.hist(data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*GsVJTAbwEPRZKhIbbp8u2g.png" /></figure><h4>Rectangular Box Plot</h4><pre>data = [np.random.normal(0, std, 100) for std in range(1, 4)]</pre><pre># rectangular box plot<br>plt.boxplot(data,vert=True,patch_artist=True);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*sO9dHDWj6WgnER_T7yM4zQ.png" /></figure><p>This wraps up the fundamental of this beautiful python library, and I hope you enjoyed learning it as much as I did while making this tutorial.</p><p>Congratulations! on completing part 3/3 of the series🎉🎉🎉</p><p>I will soon add more visualisation tutorials with slightly advanced libraries such as seaborn and plotly where we will be able to visualise more complex data. <br>Thanks for reading🙂</p><h4>Further Readings</h4><ul><li><a href="http://www.matplotlib.org/">http://www.matplotlib.org</a> — The project web page for matplotlib.</li><li><a href="https://github.com/matplotlib/matplotlib">https://github.com/matplotlib/matplotlib</a> — The source code for matplotlib.</li><li><a href="http://matplotlib.org/gallery.html">http://matplotlib.org/gallery.html</a> — A large gallery showcaseing various types of plots matplotlib can create. Highly recommended!</li><li><a href="http://www.loria.fr/~rougier/teaching/matplotlib">http://www.loria.fr/~rougier/teaching/matplotlib</a> — A good matplotlib tutorial.</li><li><a href="http://scipy-lectures.github.io/matplotlib/matplotlib.html">http://scipy-lectures.github.io/matplotlib/matplotlib.html</a> — Another good matplotlib reference</li></ul><h4>Sources</h4><ul><li><a href="https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/">https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/</a></li><li><a href="https://sites.google.com/site/ownscratchpad/datascience/matplotlib">https://sites.google.com/site/ownscratchpad/datascience/matplotlib</a></li><li><a href="https://www.southampton.ac.uk/~fangohr/training/python/notebooks/Matplotlib.html">https://www.southampton.ac.uk/~fangohr/training/python/notebooks/Matplotlib.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96a00d04497f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/data-visualization-for-absolute-beginner-part-3-3-96a00d04497f">Data Visualization for absolute beginner [part 3/3]</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Visualization for absolute beginner using python[part 2/3]]]></title>
            <link>https://medium.com/analytics-vidhya/data-visualization-for-absolute-beginner-using-python-part-2-3-a19b3751ede?source=rss-55118ee721e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a19b3751ede</guid>
            <category><![CDATA[data-visualisation]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[data-science-training]]></category>
            <dc:creator><![CDATA[Ishank Sharma]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 19:04:51 GMT</pubDate>
            <atom:updated>2020-08-23T14:29:04.713Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Visualization for absolute beginners[part 2/3]</h3><h4>Matplotlib Object-Oriented Method</h4><p>Now that we’ve covered the basics, let’s shift our focus to introduction of Matplotlib’s Object Oriented API. This will allow us to instantiate figure objects and then we can call methods from that object.</p><h4>Introduction to the Object-Oriented Method</h4><p>The idea here is to use a more formal Object-Oriented method to create figure objects and then call the respective methods or attributes of that object. This proves to be a <em>wonderful </em>practice when dealing with multiple plots.</p><p>We will now begin by creating a figure instance. Then we will add axes to that figure.</p><pre># Object oriented method<br># Create Figure (empty canvas)<br>fig = plt.figure()</pre><pre># Add set of axes to figure<br>axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)</pre><pre># Plot on that set of axes<br>axes.plot(x, y, &#39;b&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*lqDUkNouvSqLKzpBxlI4ew.png" /></figure><p><strong>NOTE : </strong>We did the same thing using plt.plot(x,y) in part 1 of this tutorial. But now using this Object-Oriented approach we are going to have a lot more control over our fig object and we can easily add more than one axes to our figure as shown below.</p><pre># Creates blank canvas<br>fig = plt.figure()</pre><pre>axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes<br>axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes</pre><pre># Larger Figure Axes 1<br>axes1.plot(x, y, &#39;b&#39;)</pre><pre># Insert Figure Axes 2<br>axes2.plot(y, x, &#39;r&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*4eQIwgGyRrsW2VEmRS8APg.png" /></figure><h4>Subplots()</h4><p>Now we are going to learn how to create subplots using the same object-oriented approach. Subplot is different because we can specify the number of rows and columns.</p><p>The plt.subplots() object acts as a more automatic axis manager.</p><p>Basic use cases:</p><pre># Use tuple unpacking to grab fig and axes<br>fig, axes = plt.subplots()</pre><pre># Use axes object to add stuff to the plot<br>axes.plot(x, y, &#39;r&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*Cvmk2YP6sYYsNPO3rVRsGQ.png" /></figure><p>Now we will specify the number of rows and columns while instantiating the subplots() object:</p><pre># Make an empty canvas of 1 by 2 subplots<br>fig, axes = plt.subplots(nrows=1, ncols=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*oNTuu2rK1Foii6z5CiFwRg.png" /></figure><pre># Axes is an array of axes to plot on<br>axes</pre><p>Out[]</p><pre>array([&lt;matplotlib.axes._subplots.AxesSubplot object at 0x111f0f8d0&gt;,&lt;matplotlib.axes._subplots.AxesSubplot object at 0x1121f5588&gt;], dtype=object)</pre><p>Recall that in part 1 we did the same thing by manually giving rows and columns, but since its an array we can actually iterate over it and directly plot the data.</p><pre>for ax in axes:<br>    ax.plot(x, y, &#39;b&#39;)</pre><pre># Display the figure object    <br>fig</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*Q1HFHeEp2HFHc5hYjDewog.png" /></figure><p>In matplotlib, the location of axes (including subplots) are specified in normalized figure coordinates. It can happen that your axis labels or titles (or sometimes even ticklabels) go outside the figure area, and are thus clipped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*m8ovHOYLwmJOwBfIu4bh6Q.png" /><figcaption>plot with overlapping labels</figcaption></figure><p>To solve this problem we can use <strong>fig.tight_layout()</strong> or <strong>plt.tight_layout()</strong> method, which on its own adjusts the positions of the axes on the figure canvas to avoid overlapping content:</p><p><strong>tight_layout() </strong>can take keyword arguments of <em>pad</em>, <em>w_pad,</em> and <em>h_pad</em>. These control the extra padding around the figure border and between subplots. The pads are specified in fraction of font size.</p><pre>plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*0Pn8pdAtUtmSfMtJFc18YQ.png" /></figure><h4>Figure size, aspect ratio, and DPI</h4><p>Matplotlib allows the aspect ratio, DPI (dots per inch), and figure size to be specified when the Figure object is created. We can use the figsize and dpi keyword arguments.</p><ul><li>figsize is a tuple of the width and height of the figure in inches</li><li>dpi is the dots-per-inch (pixels per inch).</li></ul><pre>fig = plt.figure(figsize=(8,4), dpi=100)</pre><p>Out []:</p><pre>&lt;matplotlib.figure.Figure at 0x11228ea58&gt;</pre><p>These same arguments can also be passed tosubplots function:</p><pre>fig, axes = plt.subplots(figsize=(12,3)) # 12 by 4 inches</pre><pre>axes.plot(x, y, &#39;r&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*LX4X3bl2R_VTiLrzGYft8A.png" /></figure><h4>Saving figures</h4><p>Matplotlib generates high-quality of output in the following format JPG, PNG, EPS, SVG, PDF, and PGF.</p><p>In order to save a file, we will use the savefig method in the Figure class:</p><pre>fig.savefig(&quot;filename.jpg&quot;)</pre><p>We can also optionally specify dots per inch (DPI) and choose different output formats</p><pre>fig.savefig(&quot;filename.png&quot;, dpi=200)</pre><p>Congratulations! on completing part 2 of the series head on to part 3 by clicking <a href="https://medium.com/@ishankdev/data-visualization-from-absolute-beginner-to-complete-master-part-3-3-96a00d04497f">here</a></p><h4>Sources</h4><ul><li><a href="https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/">https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/</a></li><li><a href="https://sites.google.com/site/ownscratchpad/datascience/matplotlib">https://sites.google.com/site/ownscratchpad/datascience/matplotlib</a></li><li><a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.set_xlabel.html">https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.set_xlabel.html</a></li><li><a href="https://www.southampton.ac.uk/~fangohr/training/python/notebooks/Matplotlib.html">https://www.southampton.ac.uk/~fangohr/training/python/notebooks/Matplotlib.html</a></li><li><a href="https://www.google.com/search?q=%22axes%20=%20fig.add_axes(%5B0.1,%200.1,%200.8,%200.8%5D)%20#%20left,%20bottom,%20width,%20height%20(range%200%20to%201)%22">https://www.google.com/search?q=%22axes%20=%20fig.add_axes(%5B0.1,%200.1,%200.8,%200.8%5D)%20#%20left,%20bottom,%20width,%20height%20(range%200%20to%201)%22</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a19b3751ede" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/data-visualization-for-absolute-beginner-using-python-part-2-3-a19b3751ede">Data Visualization for absolute beginner using python[part 2/3]</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Visualization from absolute beginners using python[part 1/3]]]></title>
            <link>https://medium.com/analytics-vidhya/data-visualization-from-absolute-beginners-using-python-part-1-3-3cb9253ac007?source=rss-55118ee721e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cb9253ac007</guid>
            <category><![CDATA[python-matplotlib]]></category>
            <category><![CDATA[data-science-training]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Ishank Sharma]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 19:03:05 GMT</pubDate>
            <atom:updated>2020-08-23T14:29:36.436Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Visualization for absolute beginners [part 1/3]</h3><p>The job of a Data Scientist has been ranked the number one job by glassdoor and it is an excellent career path providing not just great salary potential but an opportunity to work on some of the world’s most interesting problems!</p><p>As a matter of fact, data visualization is one of the most in-demand skill for any data scientist out there.</p><p>Data visualization in simple terms means the representation of data in a visual format like the graph, chart, etc. We need data visualization because a visual output is always easy to understand and proves to be a much better alternative over text-based data.</p><h4>Motivation</h4><p>Being an active user of matplotlib (a <em>wonderful</em> library to plot data) , I often find it difficult to follow along with the documentation, and I always had to struggle and rely on StackOverflow to do even the basic stuff. <br>Hence I decided to write down this basic tutorial to help newbies get started with this library and become better at it.</p><p><strong>So let’s get started!</strong></p><p>In this article, we will try to get a basic understanding of python library called Matplotlib. We will start off with some basic examples and learn the most fundamental commands of Matplotlib then we will gradually move to concepts of Object-Oriented Method followed by learning about labeling our plots.</p><p>For simplicity purposes, we will divide this tutorial into <strong>three parts</strong>.</p><ul><li><a href="https://medium.com/@ishankdev/data-visualization-from-absolute-beginner-to-complete-master-part-1-3-3cb9253ac007"><strong>Matplotlib for basic visualizations</strong></a></li><li><a href="https://medium.com/@ishankdev/data-visualization-from-absolute-beginner-to-complete-master-part-2-3-a19b3751ede"><strong>Matplotlib Object-Oriented API</strong></a></li><li><a href="https://medium.com/@ishankdev/data-visualization-from-absolute-beginner-to-complete-master-part-3-3-96a00d04497f"><strong>Legends Labels and Titles for making the plots readable</strong></a></li></ul><h3>Matplotlib</h3><p><strong>Introduction</strong></p><p>Matplotlib is considered as the “grandfather” library of data visualization with Python. It was created by John Hunter. John Hunter created it to replicate MatLab’s plotting potential in Python. So if you are already familiar with Matlab, Matplotlib will feel natural to you.</p><p>It is a wonderful 2D and 3D graphics library for building scientific figures.</p><p>The major pros of Matplotlib are:</p><ul><li>Most popular plotting library for python</li><li>Easy to get started for simple plots</li><li>Supports custom labels and text</li><li>High-quality output in many formats</li><li>Very customizable in general</li></ul><h4>Installing Matplotlib</h4><ul><li>We’ll need to install it with pip or conda on our command line terminal with:</li></ul><pre>pip install matplotlib</pre><p>or</p><pre>conda install matplotlib</pre><p>If you ever find yourself stuck whether you can do a certain type of plot you can always visit <a href="https://matplotlib.org/gallery/index.html">this section of the official documentation</a> and check the examples to know more about matplotlib’s capabilities. This link is probably the <strong>most helpful page </strong>that you can find on the documentation of matplotlib.</p><p>Now in the coming section, we will see how to create our own figures.</p><p>Let’s go ahead to our Jupyter Notebook to get started.</p><p><strong>Note</strong> <strong>that I will be sharing complete .ipynb file at the end of this tutorial. So just focus on understanding the concept rather than copy-pasting these commands into your notebook.</strong></p><h4>Step 1: Importing matplotlib pyplot library</h4><p>In [1]:</p><pre>import matplotlib.pyplot as plt</pre><p><a href="https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py">matplotlib.pyplot</a> is a collection of command style functions that make matplotlib work like MATLAB</p><p>You need to add the below line in order to see the plots in the notebook</p><p>In [2]:</p><pre>%matplotlib inline</pre><p>If you are using another editor, you’ll need to use: <strong>plt.show() </strong>at the end of all of your commands, which will open the plots as a popup window.</p><h4>Basic Example</h4><p>Before we begin visualisation we need some data points upon which we can perform visualization. So let’s create a simple example using two numpy arrays.</p><p>In [3]:</p><pre>import numpy as np<br>x = np.linspace(0, 5, 11)<br>y = x ** 2</pre><p>In[4]:</p><pre>x</pre><p>Out[4]:</p><pre>array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ])</pre><p>In[5]:</p><pre>y</pre><p>Out[5]:</p><pre>array([  0.  ,   0.25,   1.  ,   2.25,   4.  ,   6.25,   9.  ,  12.25,16.  ,  20.25,  25.  ])</pre><h4>Basic Matplotlib Commands</h4><p>There are two ways in which we can create plots one is functional method and the other is object oriented method. We will discuss the functional method first and then we’ll shift over to a better method i.e the object oriented method.</p><p>To create a very basic line plot, follow the below commands.</p><p>In[6]:</p><pre># FUNCTIONAL method<br>plt.plot(x, y, &#39;r&#39;) # &#39;r&#39; is the color red<br>plt.show()</pre><p>Out[6]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*Cvmk2YP6sYYsNPO3rVRsGQ.png" /></figure><p>The plot() function here accepts three arguments- the x coordinates, the y coordinates, and the color of the line. But <strong>we should note that the plot() function is a versatile command and accepts any number of arguments.</strong></p><p><strong>Fun activity</strong>: Try the below commands and see what you get as the plot output :)</p><pre>plt.plot(x, y)        # plot x and y using default line style and color<br>plt.plot(x, y, &#39;bo&#39;)  # plot x and y using blue circle markers<br>plt.plot(y)           # plot y using x as index array 0..N-1<br>plt.plot(y, &#39;r+&#39;)     # ditto, but with red plusses</pre><p>We will discuss more on linestyles and colors in the third part of this tutorial.</p><p>Let’s move on to creation of multi plots on the same canvas.</p><h4>Creating multi plots on Same Canvas</h4><p>In order to create a multi plot on the same canvas, we will use <strong>subplot </strong>which takes in the argument as number of rows, number of columns, and plot number that we are referring to.</p><p>In[7]:</p><pre># plt.subplot(nrows, ncols, plot_number)<br>plt.subplot(1,2,1)<br>plt.plot(x, y, &#39;r--&#39;) # More on color options later<br>plt.subplot(1,2,2)<br>plt.plot(y, x, &#39;g*-&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*v5Vr4Jmo6Ca_cINHX-6czw.png" /></figure><p>Notice above how we were able to create two different plots by treating the canvas as a matrix of rows and columns where each cell represents a plot.</p><p>However, the above approach is a bad practice and we would want to use a better approach to do the same that is where the more formal object-oriented approach comes into the picture which we will be covering in second part of this series.</p><p>I highly recommend you to go with the above commands on your notebook or command-line ones and try to plot on a real-world dataset and see what patterns you find through your plots.</p><p>Great! we successfully completed part 1/3 of the tutorial🎉🎉<br>Now let’s head on to part 2 by clicking <a href="https://medium.com/@ishankdev/data-visualization-from-absolute-beginner-to-complete-master-part-2-3-a19b3751ede"><strong>here</strong></a><strong>.</strong></p><h4>Sources</h4><ul><li><a href="https://sites.google.com/site/ownscratchpad/datascience/matplotlib">https://sites.google.com/site/ownscratchpad/datascience/matplotlib</a></li><li><a href="https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/">https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/</a></li><li><a href="https://www.npntraining.com/blog/matplotlib-tutorial/">https://www.npntraining.com/blog/matplotlib-tutorial/</a></li><li><a href="https://matplotlib.org/gallery/index.html">https://matplotlib.org/gallery/index.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cb9253ac007" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/data-visualization-from-absolute-beginners-using-python-part-1-3-3cb9253ac007">Data Visualization from absolute beginners using python[part 1/3]</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>