<?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 Rishabhjohri on Medium]]></title>
        <description><![CDATA[Stories by Rishabhjohri on Medium]]></description>
        <link>https://medium.com/@rishabh2000johri2?source=rss-4838d621854b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gl16DUpe11hIJRCe</url>
            <title>Stories by Rishabhjohri on Medium</title>
            <link>https://medium.com/@rishabh2000johri2?source=rss-4838d621854b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:07:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rishabh2000johri2/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[LOOPS vs RECURSION]]></title>
            <link>https://medium.com/student-technical-community-vit-vellore/loops-vs-recursion-afd1856a662?source=rss-4838d621854b------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd1856a662</guid>
            <category><![CDATA[loop-in-python]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rishabhjohri]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 13:01:31 GMT</pubDate>
            <atom:updated>2020-12-21T13:01:31.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*NoEqLDMvCVbDxpUAmZYRZA.png" /></figure><p>It’s a response often encountered during technical interviews: “OK, you solved the problem with a while loop, now do it with recursion.” Or vice versa. But which method is generally preferable?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*i9EFO14OOWEzEoE1DhP0mg.png" /></figure><p>Before answering that lets explore recursion and looping from the point of view of <em>Theory of Computation and Compiler design</em>.</p><p>There is this concept of “intermediate code generation” that uses go-to statements to create the for and while loop constructs as well as recursive construct that is readily available in high, middle level languages like C , C++, Java , Python , etc.</p><p>For example let me approach the same problem using different constructs, the problem is: Find the sum first 5 natural numbers.</p><p><strong>FOR LOOP</strong></p><pre>s=0</pre><pre>for(i=1;i≤5;i++){</pre><pre>s = s+ i }</pre><p><strong>WHILE LOOP</strong></p><pre>s=0 , i=1</pre><pre>while(i≤5){</pre><pre>s = s + i</pre><pre>i = i+1 }</pre><p><strong>REPEAT UNTIL ( DO WHILE)</strong></p><pre>s=0 , i=1</pre><pre>repeat{</pre><pre>s = s + i</pre><pre>i = i+1</pre><pre>} until ( i=5)</pre><p><strong><em>now , let’s implement it using conditional statements( if-then) and goto , that is, the intermediate code construct:</em></strong></p><ol><li>s = 0 , i = 1</li><li>s = s+i</li><li>i = i+1</li><li>if (i≤5 ) then goto 2</li><li>end</li></ol><p>Finally lets implement it using recursion , but before that let me explain the term recursion in a simple way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*ITGVyJiOXj7ccbkbLgmoqQ.png" /></figure><blockquote>recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem.</blockquote><p>consider the calculation of factorial:</p><p>n! = n*(n-1)*…*1</p><p>it can be also written as:</p><p>n! = n*(n-1)!</p><p>Also , fibonacci series can also be written as recursively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*gyLkWyQ-72JJq6DvuaJ2Qg.png" /></figure><p>f(n) = f(n-1) +f(n-2)</p><p>to terminate recursive loop we set a base case , here the base case is:</p><p>f(0) = 0 , f(1) = 1</p><p>for factorial example , the base case is 0! = 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*BiWaj90OZLmOZ6dF8CireQ.png" /></figure><p><em>Now lets approach the given problem of find sum of first 5 natural numbers using the recursion construct:</em></p><pre>f(n){</pre><pre>if (n !=0)</pre><pre>{ return (n + f(n-1))}</pre><pre>else{</pre><pre>return n} }</pre><p><em>now just set n =5 to solve the problem</em></p><p>NOW COMING BACK TO THE ORIGNAL DISCUSSION:</p><p>which is more preferable?</p><p>the answer is : it depends</p><ul><li>Some problems are very amenable to recursive solutions e.g. <a href="http://en.wikipedia.org/wiki/Quicksort">quicksort</a></li><li>Some languages don’t really support recursion e.g. <a href="http://en.wikipedia.org/wiki/Fortran#Recursion">early FORTRANs</a></li><li>Some languages assume recursion as a primary means for looping e.g. <a href="http://learnyouahaskell.com/recursion">Haskell</a></li></ul><p>It’s also worth noting that support for <a href="http://en.wikipedia.org/wiki/Tail_call">tail recursion</a> makes tail recursive and iterative loops equivalent, that is, recursion doesn’t always have to waste the stack.</p><p>Also, a recursive algorithm can always be implemented iteratively <a href="http://stackoverflow.com/questions/159590/way-to-go-from-recursion-to-iteration">by using an explicit stack</a>.</p><p>There’s no universally agreed on definition of “better” when it comes to programming, but I’ll take it to mean “easier to maintain/read.”</p><p>Recursion has more expressive power than iterative looping constructs. I say this because a while loop is equivalent to a tail recursive function and recursive functions need not be tail recursive. Powerful constructs are usually a bad thing because they allow you to do things that are difficult to read. However, recursion gives you the ability to write loops without using mutability, and to my mind mutability is much more powerful than recursion.</p><p>So, from low expressive power to high expressive power, looping constructs stack up like this:</p><ul><li>Tail recursive functions that use immutable data</li><li>Recursive functions that use immutable data</li><li>While loops that use mutable data</li><li>Tail recursive functions that use mutable data</li><li>Recursive functions that use mutable data</li></ul><p>Ideally, you’d use the least expressive constructs that you can. Of course, if your language doesn’t support tail call optimization, then that may also influence your choice of looping construct.</p><p><strong>CONCLUSION</strong></p><blockquote>Recursion is not intrinsically better or worse than loops — each has advantages and disadvantages, and those even depend on the programming language (and implementation).</blockquote><p>Technically, iterative loops fit typical computer systems better at the hardware level: at the machine code level, a loop is just a test and a conditional jump, whereas recursion (implemented naively) involves pushing a stack frame, jumping, returning, and popping back from the stack. On the other hand, many cases of recursion (especially those that are trivially equivalent to iterative loops) can be written so that the stack push / pop can be avoided. This is possible when the recursive function call is the last thing that happens in the function body before returning, and it’s commonly known as a tail call optimization (or tail recursion optimization). A properly tail-call-optimized recursive function is mostly equivalent to an iterative loop at the machine code level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*QrrtJyeW94lpYnhzfOJD3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*vyUPzVq4bqkld2uTnr2XoA.png" /></figure><p>REFERENCE:</p><p>Computerphile video: loop vs recursion on youtube :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHXNhEYqFo0o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHXNhEYqFo0o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHXNhEYqFo0o%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/da0ad28ff2c5eee3304e07f9244a0856/href">https://medium.com/media/da0ad28ff2c5eee3304e07f9244a0856/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd1856a662" width="1" height="1" alt=""><hr><p><a href="https://medium.com/student-technical-community-vit-vellore/loops-vs-recursion-afd1856a662">LOOPS vs RECURSION</a> was originally published in <a href="https://medium.com/student-technical-community-vit-vellore">Student Technical Community — VIT Vellore</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VISUALIZATION OF DIJKSTRA’S ALGORITHM Using Python]]></title>
            <link>https://medium.com/student-technical-community-vit-vellore/visualization-of-dijkstras-algorithm-using-python-39f4109674bd?source=rss-4838d621854b------2</link>
            <guid isPermaLink="false">https://medium.com/p/39f4109674bd</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rishabhjohri]]></dc:creator>
            <pubDate>Mon, 07 Dec 2020 11:10:28 GMT</pubDate>
            <atom:updated>2020-12-07T11:10:28.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*jM4CjljN4KO8igKHwzG8Pw.png" /></figure><p>In the previous semester , I studied DSA . It is a really interesting subject but many students find it quite difficult. One of the algorithm that carries a lot of weightage is the shortest path finding algorithm : DIJKSTRA’S ALGORITHM. When I studied it for the first time I found it really difficult to solve the problems related to this algorithm but by God’s grace , I was able to find really helpful YouTube videos for DSA that visualized this topic and hence I was able to perform well in the exams.</p><p>These visualization videos were animated. I always fantasized about a way by which I could visualize what I code to get a better understanding of the working of algorithm. Then I came across a really cool python library called PyGame:</p><p><a href="https://pypi.org/project/pygame/">https://pypi.org/project/pygame/</a></p><p>As python is a beginner friendly yet powerful programming language , PyGame was the Ideal choice for me , it was exactly what I was looking for!</p><p>For those of you who haven’t studied the algorithm yet:</p><p><a href="https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/">https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/</a></p><h3>CODE:</h3><pre>import pygame, sys, random, math</pre><pre>from collections import deque</pre><pre>from tkinter import messagebox, Tk</pre><pre>size = (width, height) = 640, 480</pre><pre>pygame.init()</pre><pre>win = pygame.display.set_mode(size)</pre><pre>pygame.display.set_caption(“Dijkstra’s Path Finding”)</pre><pre>clock = pygame.time.Clock()</pre><pre>cols, rows = 64, 48</pre><pre>w = width // cols</pre><pre>h = height // rows</pre><pre>grid = []</pre><pre>queue, visited = deque(), []</pre><pre>path = []</pre><pre>class Spot:</pre><pre>def __init__(self, i, j):</pre><pre>self.x, self.y = i, j</pre><pre>self.f, self.g, self.h = 0, 0, 0</pre><pre>self.neighbors = []</pre><pre>self.prev = None</pre><pre>self.wall = False</pre><pre>self.visited = False</pre><pre># if random.randint(0, 100) &lt; 20:</pre><pre># self.wall = True</pre><pre>def show(self, win, col, shape=1):</pre><pre>if self.wall == True:</pre><pre>col = (0, 0, 0)</pre><pre>if shape == 1:</pre><pre>pygame.draw.rect(win, col, (self.x * w, self.y * h, w — 1, h — 1))</pre><pre>else:</pre><pre>pygame.draw.circle(win, col, (self.x * w + w // 2, self.y * h + h // 2), w // 3)</pre><pre>def add_neighbors(self, grid):</pre><pre>if self.x &lt; cols — 1:</pre><pre>self.neighbors.append(grid[self.x + 1][self.y])</pre><pre>if self.x &gt; 0:</pre><pre>self.neighbors.append(grid[self.x — 1][self.y])</pre><pre>if self.y &lt; rows — 1:</pre><pre>self.neighbors.append(grid[self.x][self.y + 1])</pre><pre>if self.y &gt; 0:</pre><pre>self.neighbors.append(grid[self.x][self.y — 1])</pre><pre>def clickWall(pos, state):</pre><pre>i = pos[0] // w</pre><pre>j = pos[1] // h</pre><pre>grid[i][j].wall = state</pre><pre>def place(pos):</pre><pre>i = pos[0] // w</pre><pre>j = pos[1] // h</pre><pre>return w, h</pre><pre>for i in range(cols):</pre><pre>arr = []</pre><pre>for j in range(rows):</pre><pre>arr.append(Spot(i, j))</pre><pre>grid.append(arr)</pre><pre>for i in range(cols):</pre><pre>for j in range(rows):</pre><pre>grid[i][j].add_neighbors(grid)</pre><pre>start = grid[cols // 2][rows // 2]</pre><pre>end = grid[cols — 50][rows — cols // 2]</pre><pre>start.wall = False</pre><pre>end.wall = False</pre><pre>queue.append(start)</pre><pre>start.visited = True</pre><pre>def main():</pre><pre>flag = False</pre><pre>noflag = True</pre><pre>startflag = False</pre><pre>while True:</pre><pre>for event in pygame.event.get():</pre><pre>if event.type == pygame.QUIT:</pre><pre>pygame.quit()</pre><pre>sys.exit()</pre><pre>if event.type == pygame.MOUSEBUTTONUP:</pre><pre>if pygame.mouse.get_pressed(0):</pre><pre>clickWall(pygame.mouse.get_pos(), True)</pre><pre>if pygame.mouse.get_pressed(2):</pre><pre>clickWall(pygame.mouse.get_pos(), False)</pre><pre>if event.type == pygame.MOUSEMOTION:</pre><pre>if pygame.mouse.get_pressed()[0]:</pre><pre>clickWall(pygame.mouse.get_pos(), True)</pre><pre>if event.type == pygame.KEYDOWN:</pre><pre>if event.key == pygame.K_RETURN:</pre><pre>startflag = True</pre><pre>if startflag:</pre><pre>if len(queue) &gt; 0:</pre><pre>current = queue.popleft()</pre><pre>if current == end:</pre><pre>temp = current</pre><pre>while temp.prev:</pre><pre>path.append(temp.prev)</pre><pre>temp = temp.prev</pre><pre>if not flag:</pre><pre>flag = True</pre><pre>print(“Done”)</pre><pre>elif flag:</pre><pre>continue</pre><pre>if flag == False:</pre><pre>for i in current.neighbors:</pre><pre>if not i.visited and not i.wall:</pre><pre>i.visited = True</pre><pre>i.prev = current</pre><pre>queue.append(i)</pre><pre>else:</pre><pre>if noflag and not flag:</pre><pre>Tk().wm_withdraw()</pre><pre>messagebox.showinfo(“No Solution”, “There was no solution”)</pre><pre>noflag = False</pre><pre>else:</pre><pre>continue</pre><pre>win.fill((0, 20, 20))</pre><pre>for i in range(cols):</pre><pre>for j in range(rows):</pre><pre>spot = grid[i][j]</pre><pre>spot.show(win, (44, 62, 80))</pre><pre>if spot in path:</pre><pre>spot.show(win, (192, 57, 43))</pre><pre>elif spot.visited:</pre><pre>spot.show(win, (39, 174, 96))</pre><pre>if spot in queue:</pre><pre>spot.show(win, (44, 62, 80))</pre><pre>spot.show(win, (39, 174, 96), 0)</pre><pre>if spot == start:</pre><pre>spot.show(win, (0, 255, 200))</pre><pre>if spot == end:</pre><pre>spot.show(win, (0, 120, 255))</pre><pre>pygame.display.flip()</pre><pre>main()</pre><h3>NOTE:</h3><p>If you want to try running the code on your system follow these simple steps:</p><p>1) clone the code from my repository:</p><p><a href="https://github.com/rishabhjohri/Dijkstras_Pygame">https://github.com/rishabhjohri/Dijkstras_Pygame</a></p><p>2)Open the project in an IDE and open the terminal , give the command :</p><p>pip install pygame</p><p>3) run main.py</p><p>4)A pop up window will appear , press ENTER key</p><p>5) you can draw walls by using the cursor , to change the start and end point , the corresponding values in the code must be changed</p><h3>OUTPUT:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*CCJTfuwGMCkDqIo_L1oQ1A.png" /></figure><p>after pressing enter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*NoOvnuA5XIRJXaK6lgLw1w.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6fUnC_24ua8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6fUnC_24ua8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6fUnC_24ua8%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/b1173c616196cfd9447d94b32b7034a1/href">https://medium.com/media/b1173c616196cfd9447d94b32b7034a1/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39f4109674bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/student-technical-community-vit-vellore/visualization-of-dijkstras-algorithm-using-python-39f4109674bd">VISUALIZATION OF DIJKSTRA’S ALGORITHM Using Python</a> was originally published in <a href="https://medium.com/student-technical-community-vit-vellore">Student Technical Community — VIT Vellore</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DATA VISUALISATION FOR BEGINNERS]]></title>
            <link>https://medium.com/student-technical-community-vit-vellore/data-visualisation-for-beginners-abbd96d46305?source=rss-4838d621854b------2</link>
            <guid isPermaLink="false">https://medium.com/p/abbd96d46305</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rishabhjohri]]></dc:creator>
            <pubDate>Mon, 09 Nov 2020 13:05:32 GMT</pubDate>
            <atom:updated>2020-11-09T13:05:32.369Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://cainvas.ai-tech.systems/notebooks/details/?path=rishabhjohri0/dataviz_medium.ipynb"><strong>Link for code</strong></a></p><p>A great data scientist is not only a good programmer and applied mathematician but also a good story teller . His/Her main job is to derive knowledge and insight from huge amount of apparently meaningless looking data. Best way to explain and generate insight is through visualization .</p><p>Data visualization for data science and AI is what geometry is for mathematics , It is a great way for newbies to realise the power of data science and python programming in general.</p><p>In this tutorial , we will learn to draw some of the most widely used plots using matplot library in python and the meaning behind the basic functions used in the code.</p><p>Before we get started , lets cover some of the prerequisites like functions of numpy that are used in our code :</p><p>np.random.seed() takes an integer argument and uses it as a seed to generate random numbers</p><pre>np.random.normal() :</pre><pre>numpy.random.normal<strong>(</strong><em>loc=0.0</em><strong>, </strong><em>scale=1.0</em><strong>, </strong><em>size=None</em><strong>)</strong></pre><p>Draw random samples from a normal (Gaussian) distribution.</p><p>Parameters loc : <em>float or array_like of floats</em> <em>Mean (“centre”) of the distribution.</em></p><p><em>scalefloat or array_like of floats</em></p><p><em>Standard deviation (spread or “width”) of the distribution. Must be non-negative.</em></p><p><em>sizeint or tuple of ints, optional</em></p><p><em>Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.</em></p><p>Returns</p><p>outndarray or scalar</p><p>Drawn samples from the parameterized normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeDYqEdpjRXBOGPOmNHj0A.png" /></figure><pre>np.linspace()</pre><pre>numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)</pre><p>Return evenly spaced numbers over a specified interval.</p><p>Returns num evenly spaced samples, calculated over the interval [start, stop].</p><p>The endpoint of the interval can optionally be excluded.</p><p>First we are going to import the necessary libraries: (numpy and matplot lib)</p><p>We will be using pyplot ,Text , Line2D , Axe3D ,Rectangle and Polygon from respective libraries</p><pre>import numpy as np</pre><pre>import matplotlib.pyplot as plt</pre><pre>from matplotlib.text import Text</pre><pre>from matplotlib.lines import Line2D</pre><pre>from mpl_toolkits.mplot3d import Axes3D</pre><pre>from matplotlib.patches import Rectangle, Polygon</pre><p>This function helps in setting up the clip_path parameter of scatter attribute of plt(pyplot) , in simple terms clip path allows you to specify a specific region of an element to display.</p><pre>plt.rcParams[‘figure.dpi’] = 100 #here we are setting the rc parameter</pre><pre>def clip_path(ax):</pre><pre>T1 = [(0,0),(0,1),(1,1)]</pre><pre>T2 = [(0,0),(1,0),(1,1)]</pre><pre>clip1 = Polygon(T1, closed=True, transform=ax.transAxes,</pre><pre>edgecolor=’None’, facecolor=’None’)</pre><pre>clip2 = Polygon(T2, closed=True, transform=ax.transAxes,</pre><pre>edgecolor=’None’, facecolor=’None’)</pre><pre>line = Line2D([0, 1], [0, 1], transform=ax.transAxes, linewidth=0.5,</pre><pre>color=”black”, clip_on=False, zorder=50)</pre><pre>ax.add_artist(line)</pre><pre>return clip1, clip2</pre><p>Now we are going to see different types of plots :</p><p><strong>1)Scatter Plot</strong>: A scatter plot is a diagram where each value in the data set is represented by a dot.</p><pre>def scatter(ax):</pre><pre>np.random.seed(123)</pre><pre>n = 500</pre><pre>X = np.random.normal(0, 0.5, n)</pre><pre>Y = np.random.normal(0, 0.5, n)</pre><pre>S = 25</pre><pre>clip1, clip2 = clip_path(ax)</pre><pre>ax.scatter(X, Y, S, clip_path=clip1,</pre><pre>linewidth=0.75, facecolor=”None”, edgecolor=”.25&quot;)</pre><pre>ax.scatter(X, Y, S, clip_path=clip1,</pre><pre>linewidth=0.00, facecolor=”white”, edgecolor=”None”)</pre><pre>ax.scatter(X, Y, S/2, clip_path=clip1,</pre><pre>linewidth=0.00, facecolor=”black”, edgecolor=”None”, alpha=0.5)</pre><pre>ax.scatter(X, Y, S, clip_path=clip2,</pre><pre>linewidth=0.75, facecolor=”None”, edgecolor=”.25&quot;)</pre><pre>ax.scatter(X, Y, S, clip_path=clip2,</pre><pre>linewidth=0.00, facecolor=”white”, edgecolor=”None”)</pre><pre>ax.scatter(X, Y, S/2, clip_path=clip2,</pre><pre>linewidth=0.00, facecolor=”red”, edgecolor=”None”, alpha=0.5)</pre><pre>ax.set_xlabel(“Scatter plot”)</pre><pre>We have generated 500 random tuples (x,y) to serve as data for plotting, we are using the scatter()</pre><p>Function :</p><pre><em>Axes.scatter</em>(<em>self</em>, <em>x</em>, <em>y</em>, <em>s=None</em>, <em>c=None</em>, <em>marker=None</em>, <em>cmap=None</em>, <em>norm=None</em>, <em>vmin=None</em>, <em>vmax=None</em>, <em>alpha=None</em>, <em>linewidths=None</em>, <em>verts=&lt;deprecated parameter&gt;</em>, <em>edgecolors=None</em>, <em>*</em>, <em>plotnonfinite=False</em>, <em>data=None</em>, <em>**kwargs</em>)</pre><p><strong>x, y : </strong>float or array-like, shape (n, )</p><p>The data positions.</p><p><strong>S : </strong>float or array-like, shape (n, ), optional</p><p>The marker size in points**2. Default is rcParams[‘lines.markersize’] ** 2.</p><p><strong>C : </strong>array-like or list of colors or color, optional</p><p><strong>2)</strong> <strong>Line plot</strong>:</p><pre>def lineplot(ax):</pre><pre>ax.set_xlabel(“Line plot”)</pre><pre>clip1, clip2 = clip_path(ax)</pre><pre>X = np.linspace(-1,1,100)</pre><pre>Y = 0.25*np.cos(1+np.pi*X)</pre><pre>ax.plot(X, Y, color=”black”, linewidth=2, clip_path=clip1)</pre><pre>ax.fill_between(X, Y+0.25, Y-0.25, clip_path=clip1,</pre><pre>facecolor=”black”, edgecolor=”None”, alpha=0.15)</pre><pre>X = np.linspace(-1,1,100)</pre><pre>Y = 0.25*np.cos(1+np.pi*X)</pre><pre>ax.plot(X, Y, color=”red”, linewidth=2, clip_path=clip2)</pre><pre>ax.fill_between(X, Y+0.25, Y-0.25, clip_path=clip2,</pre><pre>facecolor=”red”, edgecolor=”None”, alpha=0.15)</pre><p>A line chart or line plot or line graph or curve chart is a type of chart which displays information as a series of data points called ‘markers’ connected by straight line segments.</p><p>linespace creates n equally spaced points between 2 given numbers</p><pre><em>seaborn.lineplot(*, x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator=’mean’, ci=95, n_boot=1000, seed=None, sort=True, err_style=’band’, err_kws=None, legend=’auto’, ax=None, **kwargs)</em></pre><p><strong>3)</strong> <strong>quiver plot</strong>: Plot a 2D field of arrows.</p><pre>def quiverplot(ax):</pre><pre>clip1, clip2 = clip_path(ax)</pre><pre>n = 10</pre><pre>X,Y = np.mgrid[0:n, 0:n]</pre><pre>X,Y = 2*X/(n-1)-1, 2*Y/(n-1)-1</pre><pre>T = np.arctan2(Y, X)</pre><pre>U, V = np.cos(T), np.sin(T)</pre><pre>ax.quiver(X, Y, 0.1*U, 0.1*V, scale=1, width=0.015, clip_path=clip1,</pre><pre>edgecolor=’black’, facecolor=’.9&#39;, linewidth=.5)</pre><pre>ax.quiver(X, Y, 0.1*U, 0.1*V, T-1, scale=1, width=0.015, clip_path=clip2,</pre><pre>edgecolor=’black’, linewidth=.5, cmap=”hot”)</pre><pre>ax.set_xlabel(“Quiver plot”)</pre><p><em>quiver([X, Y], U, V, [C], **kw)</em></p><p>Where X, Y define the arrow locations, U, V define the arrow directions, and C optionally sets the color.</p><pre><em>matplotlib.pyplot.quiver(*args, data=None, **kw)</em></pre><p><strong>4) Contour plot:</strong></p><p><strong>Contour plots</strong> (sometimes called<strong> Level</strong> <strong>Plots</strong>) are a way to show a three-dimensional surface on a two-dimensional plane. It graphs two predictor variables X Y on the y-axis and a response variable Z as <strong>contours</strong>. These <strong>contours</strong> are sometimes called z-slices or iso-response values.</p><pre>def contourplot(ax):</pre><pre>clip1, clip2 = clip_path(ax)</pre><pre>def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)</pre><pre>n = 100</pre><pre>x = np.linspace(-3,3,n)</pre><pre>y = np.linspace(-3,3,n)</pre><pre>X,Y = np.meshgrid(x,y)</pre><pre>Z = f(X,Y)</pre><pre>CF = ax.contourf(Z, 10, extent=[-1,+1,-1,+1], alpha=.5,</pre><pre>origin=”upper”, cmap=”gray”, zorder=-10)</pre><pre>for collection in CF.collections:</pre><pre>collection.set_clip_path(clip1)</pre><pre>CS = ax.contour(Z, 10, extent=[-1,+1,-1,+1],</pre><pre>colors=”black”, linewidths=.5, origin=”upper”)</pre><pre>for collection in CS.collections:</pre><pre>collection.set_clip_path(clip1)</pre><pre>CF = ax.contourf(Z, 10, extent=[-1,+1,-1,+1], alpha=.75,</pre><pre>origin=”upper”, cmap=”viridis”, zorder=-10)</pre><pre>for collection in CF.collections:</pre><pre>collection.set_clip_path(clip2)</pre><pre>CS = ax.contour(Z, 10, extent=[-1,+1,-1,+1],</pre><pre>colors=”white”, linewidths=.5, origin=”upper”)</pre><pre>for collection in CS.collections:</pre><pre>collection.set_clip_path(clip2)</pre><p><strong>5)Image plot:</strong></p><pre>def imageplot(ax):</pre><pre>def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)</pre><pre>n = 32</pre><pre>x = np.linspace(-3,3,n)</pre><pre>y = np.linspace(-3,3,n)</pre><pre>X,Y = np.meshgrid(x,y)</pre><pre>Z = f(X,Y)</pre><pre>clip1, clip2 = clip_path(ax)</pre><pre>ax.imshow(Z, extent=[-1,+1,-1,+1], origin=”upper”, zorder=50,</pre><pre>cmap=”gray”, interpolation=”nearest”, clip_path=clip1)</pre><pre>ax.imshow(Z, extent=[-1,+1,-1,+1], origin=”upper”,</pre><pre>cmap=”hot”, interpolation=”bicubic”, clip_path=clip2)</pre><pre>ax.set_xlabel(“Image plot”)</pre><p><strong>6)</strong> <strong>pie plot:</strong></p><pre><em>matplotlib.pyplot.pie</em>(<em>x</em>, <em>explode=None</em>, <em>labels=None</em>, <em>colors=None</em>, <em>autopct=None</em>, <em>pctdistance=0.6</em>, <em>shadow=False</em>, <em>labeldistance=1.1</em>, <em>startangle=None</em>, <em>radius=None</em>, <em>counterclock=True</em>, <em>wedgeprops=None</em>, <em>textprops=None</em>, <em>center=(0</em>, <em>0)</em>, <em>frame=False</em>, <em>rotatelabels=False</em>, <em>*</em>, <em>data=None</em>)</pre><p>Plot a pie chart.</p><p>Make a pie chart of array <em>x</em>. The fractional area of each wedge is given by x/sum(x). If sum(x) &lt; 1, then the values of <em>x</em> give the fractional area directly and the array will not be normalized. The resulting pie will have an empty wedge of size 1 - sum(x).</p><p>The wedges are plotted counterclockwise, by default starting from the x-axis.</p><pre>def pieplot(ax):</pre><pre>clip1, clip2 = clip_path(ax)</pre><pre>size = 0.3</pre><pre>vals = np.array([[60., 32.], [37., 40.], [29., 10.]])</pre><pre>cmap = plt.get_cmap(“gray”)</pre><pre>outer_colors = cmap(.1+np.arange(3)/4)</pre><pre>inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10])/12)</pre><pre>patches, _ = ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,</pre><pre>wedgeprops=dict(width=size, edgecolor=’w’))</pre><pre>for patch in patches:</pre><pre>patch.set_clip_on(True)</pre><pre>patch.set_clip_path(clip1)</pre><pre>patches, _ = ax.pie(vals.flatten(), radius=1-size, colors=inner_colors,</pre><pre>wedgeprops=dict(width=size, edgecolor=’w’))</pre><pre>for patch in patches:</pre><pre>patch.set_clip_on(True)</pre><pre>patch.set_clip_path (clip1)</pre><pre>cmap = plt.get_cmap(“tab20c”)</pre><pre>outer_colors = cmap(+np.arange(3))</pre><pre>inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))</pre><pre>patches, _ = ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,</pre><pre>wedgeprops=dict(width=size, edgecolor=’w’))</pre><pre>for patch in patches:</pre><pre>patch.set_clip_on(True)</pre><pre>patch.set_clip_path(clip2)</pre><pre>patches, _ = ax.pie(vals.flatten(), radius=1-size, colors=inner_colors,</pre><pre>wedgeprops=dict(width=size, edgecolor=’w’))</pre><pre>for patch in patches:</pre><pre>patch.set_clip_on(True)</pre><pre>patch.set_clip_path (clip2)</pre><pre>rect = Rectangle((0,0), 1, 1, transform=ax.transAxes, linewidth=0.75,</pre><pre>edgecolor=”black”, facecolor=”None”, clip_on=False)</pre><pre>ax.add_artist(rect)</pre><pre>ax.set_xlabel(“Pie plot”)</pre><p><strong>7)</strong> <strong>3 D plot:</strong></p><p>Plots data in three dimensions , that is each point has (x,y,z) coordinates.</p><pre>def threedplot(ax):</pre><pre>T1 = [(0,0),(0,1),(1,1)]</pre><pre>T2 = [(0,0),(1,0),(1,1)]</pre><pre>clip1 = Polygon(T1, closed=True, transform=ax.transAxes,</pre><pre>edgecolor=’None’, facecolor=’None’)</pre><pre>clip2 = Polygon(T2, closed=True, transform=ax.transAxes,</pre><pre>edgecolor=’None’, facecolor=’None’)</pre><pre>ax.set_axis_off()</pre><pre>ax.set_xlim(-1, 1), ax.set_ylim(-1, 1), ax.set_zlim(-2, 2)</pre><pre>X,Y= np.meshgrid(np.linspace(-1, 1, 25),</pre><pre>np.linspace(-1, 1, 25))</pre><pre>Z = np.sin(5*np.sqrt(X**2+Y**2))</pre><pre>ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=”gray”, clip_path=clip1,</pre><pre>linewidth=.25, edgecolor=”black”, vmin=-1.5, vmax=1)</pre><pre>ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=”magma”, clip_path=clip2,</pre><pre>linewidth=0, edgecolor=”black”, vmin=-1.5, vmax=1)</pre><pre>line = Line2D([0, 1], [0, 1], transform=ax.transAxes, linewidth=0.5,</pre><pre>color=”black”, clip_on=False, zorder=10)</pre><pre>ax.add_artist(line)</pre><pre>rect = Rectangle((0,0), 1, 1, transform=ax.transAxes, linewidth=0.75,</pre><pre>edgecolor=”black”, facecolor=”None”, clip_on=False)</pre><pre>ax.add_artist(rect)</pre><pre>text = Text(0.5, -0.025, “3D plot”, clip_on=False,</pre><pre>ha=”center”, va=”top”, transform=ax.transAxes)</pre><pre>ax.add_artist(text)</pre><p><strong>8) bar plot:</strong></p><pre>def barplot(ax):</pre><pre>clip1, clip2 = clip_path(ax)</pre><pre>n = 16</pre><pre>X = np.arange(n)</pre><pre>Y1 = (1–0.25*X/n) * np.random.uniform(0.25, 0.75, n)</pre><pre>Y2 = (1–0.25*X/n) * np.random.uniform(0.25, 0.75, n)</pre><pre>ax.bar(X, +Y1, 1, facecolor=’#cccccc’, edgecolor=’white’, clip_path=clip1)</pre><pre>ax.bar(X, -Y2, 1, facecolor=’#999999&#39;, edgecolor=’white’, clip_path=clip1)</pre><pre>ax.bar(X, +Y1, 1, facecolor=’#ffaaaa’, edgecolor=’white’, clip_path=clip2)</pre><pre>ax.bar(X, -Y2, 1, facecolor=’#ff7777&#39;, edgecolor=’white’, clip_path=clip2)</pre><pre>ax.set_xlim(-1,n)</pre><pre>ax.set_xlabel(“Bar plot”)</pre><p><strong>9)</strong> <strong>box plot:</strong></p><p>A <strong>box plot</strong> (also known as <strong>box and whisker plot</strong>) is a type of chart often used in explanatory data analysis to visually show the distribution of numerical data and skewness through displaying the data quartiles (or percentiles) and averages.</p><pre>def boxplot(ax):</pre><pre>clip1, clip2 = clip_path(ax)</pre><pre>n = 5</pre><pre>data = np.random.normal(0, .25, (100,n))</pre><pre>bplots = ax.boxplot(data, patch_artist=True)</pre><pre>for patch in bplots[‘boxes’]:</pre><pre>patch.set_facecolor(“0.9”)</pre><pre>for line in bplots[‘medians’]:</pre><pre>line.set_color(“black”)</pre><pre>for element in [“boxes”,”medians”,”whiskers”, “caps”, “fliers”,”means”]:</pre><pre>for item in bplots[element]:</pre><pre>item.set_clip_path(clip1)</pre><pre>bplots = ax.boxplot(data, patch_artist=True)</pre><pre>for patch in bplots[‘boxes’]:</pre><pre>patch.set_facecolor(“0.9”)</pre><pre>for line in bplots[‘medians’]:</pre><pre>line.set_color(“black”)</pre><pre>for element in [“boxes”,”medians”,”whiskers”, “caps”, “fliers”,”means”]:</pre><pre>for item in bplots[element]:</pre><pre>item.set_color(“red”)</pre><pre>try:</pre><pre>item.set_markerfacecolor (“red”)</pre><pre>item.set_markeredgecolor (“red”)</pre><pre>except:</pre><pre>pass</pre><pre>item.set_clip_path(clip2)</pre><pre>ax.set_xlim(0,n+1), ax.set_xticks([])</pre><pre>ax.set_xlabel(“Box plot”)</pre><p>Now let’s set the axis and the background and call our functions</p><pre>fig, axes = plt.subplots(3, 3, figsize=(8, 8))</pre><pre>for ax in axes.ravel():</pre><pre>ax.set(xticks=[], yticks=[], xlim=[-1,1], ylim=[-1,1])</pre><pre>axes[2,2] = plt.subplot(339, projection=”3d”)</pre><pre>lineplot(axes[0,0])</pre><pre>scatter(axes[0,1])</pre><pre>barplot(axes[0,2])</pre><pre>imageplot(axes[1,0])</pre><pre>contourplot(axes[1,1])</pre><pre>boxplot(axes[1,2])</pre><pre>quiverplot(axes[2,0])</pre><pre>pieplot(axes[2,1])</pre><pre>threedplot(axes[2,2])</pre><p><strong>OUTPUT:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*VG9FtX8QVUk9Qybqmr-hXw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abbd96d46305" width="1" height="1" alt=""><hr><p><a href="https://medium.com/student-technical-community-vit-vellore/data-visualisation-for-beginners-abbd96d46305">DATA VISUALISATION FOR BEGINNERS</a> was originally published in <a href="https://medium.com/student-technical-community-vit-vellore">Student Technical Community — VIT Vellore</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>