<?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 Sandeep Garg on Medium]]></title>
        <description><![CDATA[Stories by Sandeep Garg on Medium]]></description>
        <link>https://medium.com/@sangarg?source=rss-d29865bf9b7b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Niqx4u_IXNx-RLvQ</url>
            <title>Stories by Sandeep Garg on Medium</title>
            <link>https://medium.com/@sangarg?source=rss-d29865bf9b7b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:51:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sangarg/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[End To End Power BI Dashboard Project | AdventureWorks]]></title>
            <link>https://medium.com/@sangarg/power-bi-dashboard-project-546bb26dc437?source=rss-d29865bf9b7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/546bb26dc437</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[power-bi-dashboard]]></category>
            <category><![CDATA[dax]]></category>
            <dc:creator><![CDATA[Sandeep Garg]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 16:01:40 GMT</pubDate>
            <atom:updated>2025-04-18T06:19:08.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RvQoerdKpiPmiXAVHATGZA.png" /></figure><ol><li><strong>Situation:</strong> You’ve just been hired as a Business Intelligence Analyst by Adventure Works, a global manufacturing company that produces cycling equipment and accessories.</li><li><strong>Objective:</strong> The management team needs a way to <strong><em>track KPIs (sales, revenue, profit, returns), compare regional performance, analyze product-level trends, and identify high-value customers.</em></strong> All you’ve been given is a folder of raw csv files, which contain information about transactions, returns, products, customers, and sales territories.</li></ol><p><strong>3. Action Items : </strong>Use Power BI Desktop to:</p><ul><li>Connect and transform the raw data</li><li>Build a relational data model.</li><li>Create calculated columns and measures with DAX</li><li>Design an interactive dashboard to visualize the data</li></ul><p><strong>What is Power BI and how to download it:</strong> Microsoft Power BI is a self-service business intelligence platform, which includes both desktop and web-based applications for connecting, modeling, and visualizing data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*GeQ7MxDnLMvAGuVnHFeHng.png" /><figcaption>How to Download Power BI Desktop</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*2YIDa1cFxYW2-_1C-CiVbA.png" /><figcaption>Commonality B/W Power BI &amp; Excel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*vtzCHBHuauxpMlKqasMzAw.png" /><figcaption>Power BI Workflow</figcaption></figure><p>Power BI Desktop essentially has <strong>two </strong>distinct environments: <strong>a front-end and a back-end</strong></p><p><em>1. The front-end includes the Data, Model &amp; Report views, where most of the modeling, analysis and visualization takes place</em></p><p><em>2. The back-end includes the Power Query Editor, where raw data is extracted, transformed, and loaded to the front-end (ETL)</em></p><p>First of all I hope you able to download and installed the Power BI in your windows PC (Power BI is not available for Mac 😢). Now let’s get started and open your Power BI desktop.</p><h3>Let’s roll up your sleeves and gets your hand dirty</h3><p>If you ready Let’s down the raw data first : <a href="https://github.com/Sangarg12/Dashboard-Visualization/tree/main/Power%20BI%20Dashboard%20-%20AdventureWorks/Data%20Files">Click here for data</a></p><h3><strong><em>Step 1: I</em></strong>mport &amp; Transform raw data.</h3><ol><li>Create queries to connect to all the given data .csv files (list given below ) one by one using <strong><em>Get Data &gt;&gt; Text/CSV (as shown in pic below) </em></strong>and then click on the transform button instead of loading the data directly, once you clicked on the transform button power query editor will be opened up.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYfwXipF7s9qRXOyIF8EDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*P2Y7g3m61UYvg2ReBOsNwQ.png" /></figure><ol><li><strong>Connect to AdventurWorks Territory Lookup.csv file:</strong><br>Rename the table to ‘<strong>Territory Lookup</strong>’ and make sure that headers have been promoted.</li><li><strong>Connect to the AdventurWorks Product Lookup .csv file:</strong><br>a) Rename the table to ‘<strong>Product Lookup</strong>’ and make sure that headers have been promoted and check all the column datatype.<br>b) Changed datatype from whole number to currency data type for<strong><em> ‘Product Cost’ &amp; ‘Product Price’ </em></strong>Column <br>c) Removed product size column (coz not required) <br>d) Added a new column ‘<strong><em>SKU Type’</em></strong> to extract all characters before the second instead of first dash (e.g. A-B-C and we need A-B) from the ‘<em>Product SKU</em>’ column using extract function text before delimiter from add column section. <br>e) Replaced zeros in the ‘Product Style<strong>’</strong> column with “NA”.</li><li><strong>Connect to the AdventureWorks Customer Lookup .csv file: </strong><br>a) Rename the table to ‘<strong>Customer Lookup</strong>’ and make sure that headers have been promoted and check all the column datatype.<br>b) Format the columns <strong>‘prefix, first name, last name’</strong> from all capital letter to only first capital letter using <strong><em>‘Capitalize each word’</em></strong> transform function.<br>b) Create new column as <strong>‘Full name’</strong> from <strong>‘prefix, first name, last name’ </strong>columns using <strong><em>merge columns function from add column section</em></strong>. Note: order of column selection is important while concatenating the columns to create a new column.<br>c) Further more extract the domain name from the ‘<strong>EmailAddress</strong>’ column using<strong><em> extract text before/after delimiter function transform section</em></strong> to check from where customer came from and named the column as <strong>‘Domain Name’</strong></li><li><strong>Connect to the AdventureWorks Calendar Lookup .csv file:</strong><br>a) Rename the table to ‘<strong>Calendar Lookup</strong>’ and make sure that headers have been promoted and check whether column is date type or not.<br>b) Use the date tools in the query editor to add the following columns:<br>Start of Week (starting Sunday)<br>Name of Day<br>Start of Month<br>Name of Month<br>Quarter of Year<br>Year</li></ol><p>Note: If you don’t have calendar table then you can also create a custom calendar table in power BI.</p><pre>From date columm added more columns given below<br>For week start date: Date.StartOfWeek([Date],Day.Monday)<br>For year: Date.Year([Date])<br>For quarter: Date.QuarterOfYear([Date])<br>For month: Date.MonthOfYear([Date])<br>For week of year: Date.WeekOfYear([Date])<br>and many more<br><br>For customer rolling calendar table:<br><br>Create a new blank query and enter any start date like<br>=#date(2024,1,1)      (act as Source)<br>Then using M formula as given below you can create an rolling calendar table<br><br>= List.Dates( Source,<br>Number.From(DateTime.LocalNow()) - Number.From(Source),<br>#duration(1,0,0,0)<br>)<br><br>here duration is for steps between each dates which is 1 day.</pre><p>6. <strong>Connect to all the AdventureWorks Sales Data (2020,21,22) .csv file :</strong> <br>a) Using folder connection appended all the sales data csv files (present within same folder with same structure) so that in case in future new sales data file comes in folder it will automatically appended in the query with refresh. Folder connection is efficient and better way to append the data in power BI if we are getting the fact tables on recurring basis.</p><p>b) Rename the table to Sales data and make sure that headers have been promoted and check whether columns date types is correct or not.</p><p>7. <strong>Connect to AdventureWorks Returns Data .csv file:</strong><br>a) Rename the table to Returns data and make sure that headers have been promoted and check whether columns date types is correct or not.</p><p>8. <strong>Similarly Connect to Adventure Works Product Categories and Subcategories Lookup .csv files.</strong></p><p>Tip to reduce the time of connection/query refresh: Disable report refresh for any static data source (if tables/data source doesn’t update frequently).</p><h3>Objective 2: Build Relational Data Model</h3><p><strong>1)</strong> In the <strong>MODEL</strong> view, arrange your tables with the lookup tables above the data tables</p><ul><li>Connect <strong>Sales Data</strong> to <strong>Customer Lookup</strong>, <strong>Product Lookup</strong>, and <strong>Territory Lookup </strong>tables using valid primary/foreign keys</li><li>Connect <strong>Sales Data</strong> to <strong>Calendar</strong> using both date fields (order date to calendar date column).</li><li>Connect <strong>Return Data</strong> to <strong>Products</strong>, <strong>Calendar</strong>, and <strong>Territory lookup tables </strong>using valid primary/foreign keys.</li><li>Connect <strong>Return Data</strong> to <strong>Calendar</strong> using both date fields (Return date to calendar date column).</li><li>Connect ‘<strong>Product subcategories</strong>’ to <strong>Product Lookup </strong>and similarly<strong> ‘Product category Lookup’</strong> to ‘<strong>Product subcategories</strong>’ as a “snowflake” schema.</li></ul><p><strong>2)</strong> Confirm the following:</p><ul><li>All relationships follow <strong>one-to-many</strong> cardinality, with primary keys (1) on the lookup side and foreign keys (*) on the data side</li><li>Filters are all <strong>one-way</strong> (no two-way filters)</li><li>Filter context flows “<strong>downstream</strong>” from lookup tables to data tables</li><li>Data tables are connected via <strong>shared lookup tables</strong> (<em>not directly to each other</em>)</li></ul><p><strong>3)</strong> Hide all <strong>foreign keys</strong> in both fact data tables from report view to avoid confusion while using the column.<br>(for example if your use the territory key from return data table and if any region don’t have any returns then for those regions sales will not appear because here filter is moving from returns data to territory lookup and then filtering out the sales data which will not shows corrects picture but if we use the territory key from territory lookup table then it have all the key and sales return data will shows correct values)</p><p><strong>4)</strong> In the <strong>DATA</strong> view, complete the following:</p><ul><li>Update <em>all</em> date fields (across all tables) to the “<strong>M/d/yyyy</strong>” format using the formatting tools in the <strong>Modeling</strong> tab</li><li>Update “<em>product_retail_price</em>”, “<em>product_cost</em>”, and “<em>discount_price</em>” etc to <strong>Currency ($ English)</strong> format.</li><li>In the <strong>Territory </strong>table, categorize “<em>Continent</em>” as <strong>Continent</strong>, “<em>Country</em>” as <strong>Country/Region and </strong>created territory hierarchy column with continent-&gt; country -&gt;region in territory lookup table</li></ul><p><strong>5)</strong> Save your .pbix file</p><p>6) Solution Screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0XFpq957XKvQmBqcPbBAA.png" /><figcaption>Power BI Data Model</figcaption></figure><h3>Objective 3: Let’s create required calculated columns and measures with DAX</h3><blockquote>Data Analysis Expressions (DAX) can be used to create both calculated columns and measures. Calculated columns produce new values within tables, and measures are evaluated at the report-level based on filter context.</blockquote><p>At report level create the following Measures</p><ol><li>Total Revenue : SUMX(‘Sales Data’, ‘Sales Data’[OrderQuantity] * RELATED(‘Product Lookup’[ProductPrice]))</li><li>Total Orders = DISTINCTCOUNT( ‘Sales Data’[OrderNumber] )</li><li>Total Customer = DISTINCTCOUNT(‘Sales Data’[CustomerKey])</li><li>Total Returns = SUM( ‘Returns Data’[ReturnQuantity] )</li><li>Total Profit = [Total Revenue] — [Total Cost]</li><li>Previous Month Revenue = CALCULATE([Total Revenue], DATEADD(‘Calendar Lookup’[Date],-1,MONTH))</li><li>Previous Month Returns = CALCULATE([Total Returns],DATEADD(‘Calendar Lookup’[Date],-1,MONTH))</li><li>Previous Month Profit = CALCULATE( [Total Profit], DATEADD(‘Calendar Lookup’[Date],-1,MONTH))</li><li>Previous month orders = CALCULATE([Total Orders], DATEADD(‘Calendar Lookup’[Date],-1,MONTH))</li><li>Revenue Target = [Previous Month Revenue] * 1.1</li><li>Profit Target = [Previous Month Profit] * 1.1</li><li>Order Target = [Previous month orders] *1.1</li><li>Avg Retail Price =AVERAGE(‘Product Lookup’[ProductPrice])</li><li>Quantity Sold =SUM( ‘Sales Data’[OrderQuantity])</li><li>Returned Quantity =SUM(‘Returns Data’[ReturnQuantity])</li><li>Return Rate = DIVIDE([Returned Quantity],[Quantity Sold],”No Sales”)</li><li>YTD Revenue = CALCULATE( [Total Revenue], DATESYTD(‘Calendar Lookup’[Date]))</li><li>90 Days Rolling Revenue = CALCULATE( [Total Revenue] , DATESINPERIOD( ‘Calendar Lookup’[Date],LASTDATE(‘Calendar Lookup’[Date]) , -90, DAY))</li><li>Total Revenue (customer detail) = IF(HASONEVALUE(‘Customer Lookup’[CustomerKey]),[Total Revenue],”-”)</li><li>Total orders (customer detail) = IF( HASONEVALUE(‘Customer Lookup’[CustomerKey]), [Total Orders],”-”)</li><li>Revenue Per Customer = DIVIDE([Total Revenue],[Total Customer])</li></ol><h3>Objective 4: Finally last step designing &amp; developing an interactive Power BI dashboard</h3><blockquote>Note: Before designing any dashboard you should always remember few things for better story telling &amp; decision making for end users:</blockquote><ol><li>Who is the end user? What are their key business goals and objective?</li><li>What do you want to communicate?<br>a) Comparison : like using Bar chart, line chart, Area chart etc.<br>b) Distribution : like using Histogram, Box Plot, Map &amp; Scatter Plot etc.<br>c) Composition : Pie chart, Donut chart, Heat map etc.<br>d) Relationship : Like scatter plot, bubble chart and correlation matrix etc.</li><li>What type of data and level of details you working with?</li></ol><p>Here our business objective is very clear also, here we assuming that our end user are from executive level to analyst level and here we are using the transactional level data for each orders placed and returned.</p><ol><li><strong><em>Track KPIs (sales, revenue, profit, returns):</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RvQoerdKpiPmiXAVHATGZA.png" /><figcaption>Executive View</figcaption></figure><p>2. R<strong><em>egional performance:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbcZ9ETOybEROUTIqe7-ZQ.png" /></figure><p>3. A<strong><em>nalyze product-level trends:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W15jmB9UzriEZHZQnavjeA.png" /></figure><p>4. I<strong><em>dentify high-value customers:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nN5hQyKcCCc5YODDABYxQQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=546bb26dc437" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Problem: Explode the data using SQL]]></title>
            <link>https://medium.com/@sangarg/explode-the-data-using-sql-462bad772a58?source=rss-d29865bf9b7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/462bad772a58</guid>
            <category><![CDATA[recursive-cte]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[self-join]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-queries]]></category>
            <dc:creator><![CDATA[Sandeep Garg]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 16:15:19 GMT</pubDate>
            <atom:updated>2024-11-26T16:16:16.900Z</atom:updated>
            <content:encoded><![CDATA[<p>Question: Print the numbers, number of times equal to its own value. Sample output is as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/75/1*C62IPYUdlZC-aGR2GtN7jw.png" /><figcaption>Sample output</figcaption></figure><p>Let’s rollup your sleeves to write a query to solve this problem</p><pre>create table num <br>( n  int );<br><br>insert into num values <br>(1),<br>(2),<br>(3),<br>(4),<br>(5),<br>(7);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*pwkgJgT1NLpy0EP5e7luXQ.png" /><figcaption>Input table</figcaption></figure><p><strong>Method 1 : Using recursive method</strong></p><pre>with cte as<br>(select n, 1 as counter from num<br> union all <br> select n, counter+1 from cte<br> where counter+1 &lt;= n<br> )<br><br> select n from cte<br> order by n</pre><p>Here using recursive CTE we are creating the loop to explode the numbers equal to its own value.</p><ol><li>The first part of the CTE (select n, 1 as counter from num) initializes the recursion. It selects numbers ( n ) from the num table and starts a counter at 1 for each number.</li><li><strong>Recursive Case</strong>: The second part (select n, counter+1 from cte where counter+1 &lt;= n) increments the counter by 1 in each recursion. This continues as long as the incremented counter is less than or equal to the original number ( n ).</li><li><strong>Final Selection</strong>: The main select query retrieves the numbers ( n ) produced by the CTE and orders them in ascending order for the desired final output.</li></ol><p><strong>Method 2: (Self Join)</strong></p><pre>select n1.n from num as n1<br> join num as n2 on n1.n &gt;= n2.n<br> order by n1.n</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*jYZIblDctnocCYOYTYHG3w.png" /></figure><p>Here without using recursive CTE, we can achieve the same output using self join <strong><em>but it have one limitation that it won’t work as expected if the numbers are not consecutive in the table.</em></strong></p><p>As you can see in the above snip till the time numbers are consecutive output is as expected but for value 7 its only 6 times instead of 7 times coz we have only total 6 entries in the table, if we have the total number of entries in table equal to max value of the table then we can use the self join instead of recursive CTE to achieve the same output.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=462bad772a58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advance SQL Interview Question 1]]></title>
            <link>https://medium.com/@sangarg/advance-sql-interview-question-1-0018cd7324d1?source=rss-d29865bf9b7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0018cd7324d1</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[advanced-sql]]></category>
            <category><![CDATA[sql-programming]]></category>
            <category><![CDATA[sql-interview-questions]]></category>
            <category><![CDATA[sql-query-questions]]></category>
            <dc:creator><![CDATA[Sandeep Garg]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 10:44:33 GMT</pubDate>
            <atom:updated>2024-11-21T10:45:17.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9vSC3kSrt_rLcWDYY2RIWQ.png" /></figure><p>On an online recruiting platform, each recruiting company can make a request for their candidates to complete a personalized skill assessment. The assessment can contain tasks in 3 categories: <strong>SQL, Algo, Bug fixing</strong>. Following the assessment, the company receives a report containing for for each candidate</p><p>Their declared years of experience (an integer between 0 to 100) and their score in each category. The score is the number of points from 0 to 100 or <strong>Null </strong><em>which means there was no task in this category.</em></p><p>You’re given a table, assessments with following structure:</p><pre>create table assessments<br>(<br>id int,<br>experience int,<br>sql int,<br>algo int,<br>bug_fixing int<br>)</pre><p><strong>Query should return experience of each candidate, numbers of assessments achieved perfect maximum score and total number of candidate for each experience. Below is the given output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*d2FkzagZKcnEPODpMvia0A.png" /></figure><p>Data present in table:</p><pre>insert into assessments values <br>(1,3,100,null,50),<br>(2,5,null,100,100),<br>(3,1,100,100,100),<br>(4,5,100,50,null),<br>(5,5,100,100,100),<br>(6,2,null,null,null),<br>(7,20,null,null,20),<br>(8,7,100,null,100),<br>(9,3,100,50,null),<br>(10,2,40,100,100);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*4Jmt9V4HN4JH0IM4IMESIw.png" /><figcaption>select * from assessments table</figcaption></figure><p>Soultion Approach:</p><pre>with cte as <br>(select experience,<br>case when sql = 100 then 1<br>     when sql is null then 1<br>  else 0 end as sql_u,<br>case when algo = 100 then 1<br>     when algo is null then 1<br>  else 0 end as algo_u,<br>case when bug_fixing = 100 then 1<br>     when bug_fixing is null then 1<br>  else 0 end as bug_fixing_u<br>from assessments )</pre><ol><li>Here first using case statement we are trying to flag the perfect score for each category. Note here for Null we are considering as perfect score since Null means where candidate is not asked to take the test on particular category.</li><li>We did the same thing for each given 3 categories.</li></ol><pre>select <br>experience<br>,sum(case when sql_u+algo_u+bug_fixing_u = 3 then 1 else 0 end) as perfect_score_flag<br>,count(experience) as total_candidate<br>from cte<br>group by experience</pre><p>3. Now we are flagging if sql_u+algo_u+bug_fixing_u = 3 else 0 to get the sum of those line items who have perfect score to get the column how many perfect score are there for each level of experienced candidate.</p><p>4. Total_candidate we can find using count function which is grouped on the experience level.</p><p>5. Hurray : Here is the final solution as per the ask.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*d2FkzagZKcnEPODpMvia0A.png" /><figcaption>Query Final Output</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0018cd7324d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualization mpg data set In R, GGplot2::mpg]]></title>
            <link>https://medium.com/sangarg/visualization-mpg-data-set-in-r-ggplot2-mpg-708664558e9b?source=rss-d29865bf9b7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/708664558e9b</guid>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[blogging]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Sandeep Garg]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 15:20:06 GMT</pubDate>
            <atom:updated>2020-03-22T04:10:16.149Z</atom:updated>
            <content:encoded><![CDATA[<h3>Visualization Of mpg data set In R, GGplot2::mpg</h3><p><em>This data set contains a subset of the fuel economy data.It contains only models which had a new release every year between 1999 and 2008 .</em></p><p>you can download or check data set for mpg in below mentioned link:</p><p><a href="https://vincentarelbundock.github.io/Rdatasets/datasets.html">https://vincentarelbundock.github.io/Rdatasets/datasets.html</a></p><p>NOTE: search&gt; mpg after opening the link then you can download the data set.</p><h3><strong>Lets Start R program to visualize the data set:</strong></h3><p>library(tidyverse) &gt; ggplot2::mpg</p><p><strong>#Format of a data set: Data frame with 234 rows and 11 variables</strong><br>1 manufacturer<br>2 model &gt; model name<br>3 displ &gt; engine displacement, in litres or size of engine<br>4 year &gt; year of manufacture<br>5 cyl &gt; number of cylinders<br>6 trans &gt; type of transmission<br>7 drv &gt; f = front-wheel drive, r = rear wheel drive, 4 = 4 wheel drive<br>8 cty &gt; city miles per gallon<br>9 hwy &gt; highway miles per gallon or efficiency<br>10 fl &gt; fuel type<br>11 class &gt; “type” of car</p><p><strong><em>#Lets see whats makes difference of size of cyl on efficency of car</em></strong></p><blockquote>ggplot2:: ggplot(data = mpg)+aes(x=displ,y= hwy) +geom_point()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*xYi38xWNVxMQVQcJkQkZwA.jpeg" /><figcaption><strong>This indicates that efficiency of car is inversely proportional to size of engine.</strong></figcaption></figure><p><strong>#Lets visualize it in more efficient way:</strong></p><blockquote>ggplot(data = mpg)+aes(x=displ,y=hwy,color=class)+geom_point()+<br> facet_wrap(.~year)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6m-GFfPQTk3KJn0WQZ6S-w.jpeg" /><figcaption><strong>Cylinders VS efficiency getting increased over year from 1999 to 2008</strong></figcaption></figure><p>NOTE: In above graph we can also note that we have some outliers where some cars have cylinders more than or equal to 6 but still have good efficiency.</p><h3><strong>#Lets see whats is impact of drive type of efficiency.</strong></h3><blockquote>ggplot(data=mpg)+geom_jitter(aes(x=displ,y=hwy,color=drv),show.legend = FALSE) + geom_smooth(mapping = aes(x=displ,y=hwy))+<br> facet_wrap(.~drv)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipDcWEYNDXyKIuXSdxc1uw.jpeg" /></figure><p><em>Efficiency is better for front type wheel drive than rear and four wheel drive.</em></p><blockquote>table(mpg$manufacturer) <em>#Gives the list of manufacturer</em></blockquote><blockquote>ggplot(data=mpg) + geom_bar(mapping=aes(x=manufacturer,fill=manufacturer))</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoCmTjdTmwzvFuDk47nYaQ.jpeg" /><figcaption><strong>Manufacturers counts</strong></figcaption></figure><h3><strong>#Car classes Vs Manufacturer</strong></h3><p>ggplot(data=mpg) +geom_bar(mapping=aes(x=class,fill=manufacturer),color=”black”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46uvJGYQE013LOSOw1RGWg.jpeg" /><figcaption><strong>Class VS manufacturer</strong></figcaption></figure><p>GGPLOT2 library is “Grammar of graphics” which is very dynamic and efficient package for visualization. As here we see that with using ggplot how we extract useful information from tidy or untidy data set.</p><p>Later we are going to learn more about R and package and how to use them.</p><p>Stay tuned!!! and Thanks for giving time to read this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=708664558e9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sangarg/visualization-mpg-data-set-in-r-ggplot2-mpg-708664558e9b">Visualization mpg data set In R, GGplot2::mpg</a> was originally published in <a href="https://medium.com/sangarg">sangarg</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>