Piyush Ranjan
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: Introduction description: duration: 120 card_type: cue_card --- ### DataViz - 3 (1 hour 40 minutes) #### Content - Quizzes - Quiz 1 (CC) - Quiz 2 (Subplots) - Multivariate Data Visualization - CCN - CNN - NNN - CCC - JointPlot - Pairplots - Correlation and heatmap --- title: Quiz-1 description: duration: 60 card_type: quiz_card --- # Question Suppose in a 2x3 (2 rows 3 columns) subplot, we want to create a plot to span across the first row. What would be the right code for this? # Choices - [x] plt.subplot(2,1,1) - [ ] plt.subplot(1,2,1) - [ ] plt.subplot(2,2,1) - [ ] plt.subplot(2,3,1) --- title: Quiz-1 explanation, Multivariate plots description: duration: 3000 card_type: cue_card --- #### Quiz-1 explanation To create a subplot across first row, we think in terms of 1 columns and remaining rows. Hence, `plt.subplot(2,1,1)` will divide it into 2 rows and 1 column, and plot the data in the 1st row (spanning across the 1st row). #### Importing the data Code: ``` python= !gdown https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/021/299/original/final_vg1_-_final_vg_%281%29.csv?1670840166 -O vgsales.csv ``` > Output: ``` Downloading... From: https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/021/299/original/final_vg1_-_final_vg_%281%29.csv?1670840166 To: /content/vgsales.csv 100% 2.04M/2.04M [00:01<00:00, 1.76MB/s] ``` Code: ``` python= import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns ``` ``` python= data = pd.read_csv('vgsales.csv') data.head() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/103/original/Data_Viz_3.png?1695824440" width="650" height="180"> If you remember, `Genres`, `Publisher` and `Platform` were categorical values Hence similar to last lecture, we will use top 3 of each to make our analysis easier Code: ``` python= top3_pub = data['Publisher'].value_counts().index[:3] top3_gen = data['Genre'].value_counts().index[:3] top3_plat = data['Platform'].value_counts().index[:3] top3_data = data.loc[(data["Publisher"].isin(top3_pub)) & (data["Platform"].isin(top3_plat)) & (data['Genre'].isin(top3_gen))] top3_data ``` <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/104/original/2.png?1695824513" width="700" height="250"> ### Multivariate (30-40 minutes) Let's try to add 3rd variable on the top of the plots we have seen so far ### NNC #### How can we visualize the correlation between NA and EU, but for different genres? Here, we have two numerical and one categorical variable! Numerical-Numerical → Scatterplot, need to add info about one categorical variable Numerical-Categorical → Boxplot, need to add info about one numerical variable #### Let's ask two questions - Is it Possible to add information about a continuous variable upon boxplots? - Perhaps No - Is it Possible to add information about a categorical variable on scatterplot? - Yes, use colors **Solution:** Scatterplot with color Code: ``` python= plt.figure(figsize=(7,7)) sns.scatterplot(x='NA_Sales', y='EU_Sales',hue='Publisher',data=top3_data) plt.xticks(fontsize=15) plt.yticks(fontsize=15) plt.xlabel('NA Sales',fontsize=15) plt.ylabel('EU Sales',fontsize=15) plt.title('NA vs EU, per Genre', fontsize=15) plt.show() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/105/original/3.png?1695824652" width="400" height="350"> Inferences: - If we see this plot, we can notice now that Namco has lower sales correlation, while Activision has a concentrated positive correlation - EA also has positive correlation, but it's more spread compared to Activision ### CCN #### Now, how will you visualize Global Sales for each publisher, but separated by Genres? We have two categorical and one numerical data here! - Categorical-Categorical → Stacked Barplot, need to add info about one continuous feature - Categorical-Numerical → Boxplots, need to add categorical variable Which one is easier and possible? We can add one categorical variable by "dodging" multiple boxplots **Solution:** Dodged Boxplots Code: ``` python plt.figure(figsize=(15,10)) sns.boxplot(x='Publisher',y='Global_Sales',hue='Genre',data=top3_data) plt.xlabel('Genre', fontsize=12) plt.ylabel('Global Sales', fontsize=12) plt.xticks(fontsize=12) plt.yticks(fontsize=12) plt.title('Global Sales for each Publisher, Genre wise', fontsize=15) plt.show() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/106/original/4.png?1695824753" width="400" height="300"> Inferences: - Namco has lower median sales in every Genre as compared to all publishers - Looking at `Action` Genre, even though EA and Activision has almost similar medians, Action is more spread in EA - An interesting thing to notice here is that, for each of the three publishers, three different genre of games have higher sales median: - Namco: Action - Activision: Misc - EA: Sports --- title: Quiz-2 description: duration: 60 card_type: quiz_card --- # Question We are analyzing the results of the Olympics, and want to find the count of gold, silver and bronze medals won by each country. Which will be the preferred plot? # Choices - [ ] Bar Plot - [ ] Pie Chart - [x] Dodged Barplot - [ ] Scatter Plot --- title: Quiz-2 explanation, Multivariate NNN description: duration: 900 card_type: cue_card --- #### Quiz-2 explanation We are comparing two categorical variables here (medal type and country). The best way to compare this would be a dodged barplot. ### NNN So far we have seen how NA and EU are correlated with each other. But how can we compare the data when we have 3 numerical variables? #### Say, the question is, how does rank affect the correlation between NA and EU Sales? We have used scatter plot for two numerical features, we have two options here - Make a 3D Scatterplot → nice for 3D viz, but tough to report/show in static setting - Add info about 3rd feature on the 2D scatter plot itself → Bubble Chart Code: ``` python= plt.figure(figsize=(15,10)) # sns.scatterplot(x=data['NA_Sales'], y=data['JP_Sales'],data=top3_data, size=data['Rank'], sizes=(1, 200)) sns.scatterplot(x='NA_Sales', y='JP_Sales', size='Rank', sizes=(1, 200), data=data) plt.xlabel('NA_Sales',fontsize=10) plt.ylabel('JP Sales', fontsize=10) plt.title('NA vs JP Sales, based on ranking of games', fontsize=15) plt.show() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/108/original/5.png?1695825160" width="400" height="300"> Inferences: - Now interestingly, we can notice that higher ranking games are actually on the lower scale of sales, while lower ranking games are high on the sales side ### Joint Plot (10-15 minutes) #### Let's see a few more plots that we can visualize using `seaborn` #### Joint Plot - It draws a plot of two variables - It shows scatter, histogram and KDE graphs in the same plot. #### Let's check it out - We will take **`NA_Sales` as x-coordinates** and **`EU_Sales` as y-coordinates** - We can select from different values for **parameter `kind`** and it **will plot accordingly** - "scatter" | "kde" | "hist" | "hex" | "reg" | "resid" - We will set **parameter `kind`** to **`'reg'`** here Code: ``` python= sns.jointplot(x='NA_Sales', y='EU_Sales', data=top3_data) plt.show() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/109/original/6.png?1695826203" width="400" height="350"> #### As we can see here: - `jointplot` plots **scatter, histogram and KDE in the same graph** when we set **`kind=reg`** - Scatter shows the **scattering of (`NA_Sales`, `EU_Sales`) pairs as (x, y) points** - Histogram and KDE shows the separate distributions of `NA_Sales` and `EU_Sales` in the data #### We can also add hue to Joint Plot - Let's check how the 3 Genres of games are distributed in terms of `NA_Sales` and `EU_Sales` Code: ``` python= sns.jointplot(x='NA_Sales', y='EU_Sales', data=top3_data, hue='Genre') plt.show() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/110/original/7.png?1695826285" width="400" height="350"> --- title: Pair plot description: duration: 1000 card_type: cue_card --- ### Pair Plot (10-15 minutes) - `pairplot()` in `seaborn` creates a **grid of Axes by default** - Each numeric attribute in `data` is shared across the y-axes across a single row and the x-axes across a single column. - It displays a **scatterplot between each pair of attributes in the data** with different **hue** for each category #### Since, the diagonal plots belong to same attribute at both x and y axis, they are treated differently - A univariate distribution plot is drawn to show the marginal distribution of the data in each column. #### Let's check it out Code: ``` python= sns.pairplot(data=top3_data, hue='Genre') plt.show() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/112/original/8_1.png?1695826462" width="600" height="300"> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/113/original/8_2.png?1695826495" width="600" height="300"> #### Notice that: - It is **like a scatterplot of video games with `hue='Genre'`** - But the **scatter is plotted between every pair of attributes** - **Colour Legends** for each genre category are given on **right side** - It shows **relation between each pair of attributes** #### Diagonal plots are different from scatterplots - Because x and y axis have same attribute - Diagonal plots show a univariate curve category-wise for each attribute #### It is also possible to show a subset of variables or plot different variables on the rows and columns - Feel free to experiment this on your own --- title: Correlations, Heatmap description: duration: 900 card_type: cue_card --- ### Finding correlations among attributes (15-20 minutes) - We can find the level of correlation b/w different attributes (variables) #### But what exactly is a correlation? - Two variables are correlated when **they change in same/opposite direction** #### We can check coefficient of correlation using `corr()` Code: ``` python= top3_data.corr() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/114/original/9.png?1695826611" width="600" height="300"> - Higher the **MAGNITUDE** of coefficient of correlation, more the variables are **correlated** - The **sign just determines the direction of change** - `+` means increase in value of one variable causes increase in value of other variable - `-` means increase in value of one variable causes decrease in value of other variable, and vice versa #### As you can see, `Global Sales` and `Rank` have the highest correlation coeff of -0.91 #### Let's plot it using scatter plot Code: ``` python= sns.scatterplot(x= 'Global_Sales', y= 'Rank', data = top3_data) plt.show() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/116/original/10.png?1695826696" width="400" height="300"> #### But Remember **Correlation does NOT mean Causation** - We cannot conclude that change in values of a variable is causing change in values of other variable #### Now, Let's look at a way to visualize correlation among variables ### Heat Map (10-15 minutes) - A heat map plots rectangular data as a color-encoded matrix. - **Stronger the colour, stronger the correlation b/w the variables** #### Let's plot a Heat Map using correlation coefficient matrix generated using `corr()` Code: ``` python= sns.heatmap(top3_data.corr(), cmap= "Blues", annot=True) plt.show() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/117/original/11.png?1695826779" width="400" height="300"> - **`annot=True`** is for writing correlation coeff inside each cell - #### You can change the colours of cells in Heat Map if you like - There are a lot of options available! Code: ``` python print(plt.colormaps()) ``` > Output: ``` ['magma', 'inferno', 'plasma', 'viridis', 'cividis', 'twilight', 'twilight_shifted', 'turbo', 'Blues', 'BrBG', 'BuGn', 'BuPu', 'CMRmap', 'GnBu', 'Greens', 'Greys', 'OrRd', 'Oranges', 'PRGn', 'PiYG', 'PuBu', 'PuBuGn', 'PuOr', 'PuRd', 'Purples', 'RdBu', 'RdGy', 'RdPu', 'RdYlBu', 'RdYlGn', 'Reds', 'Spectral', 'Wistia', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'afmhot', 'autumn', 'binary', 'bone', 'brg', 'bwr', 'cool', 'coolwarm', 'copper', 'cubehelix', 'flag', 'gist_earth', 'gist_gray', 'gist_heat', 'gist_ncar', 'gist_rainbow', 'gist_stern', 'gist_yarg', 'gnuplot', 'gnuplot2', 'gray', 'hot', 'hsv', 'jet', 'nipy_spectral', 'ocean', 'pink', 'prism', 'rainbow', 'seismic', 'spring', 'summer', 'terrain', 'winter', 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c', 'magma_r', 'inferno_r', 'plasma_r', 'viridis_r', 'cividis_r', 'twilight_r', 'twilight_shifted_r', 'turbo_r', 'Blues_r', 'BrBG_r', 'BuGn_r', 'BuPu_r', 'CMRmap_r', 'GnBu_r', 'Greens_r', 'Greys_r', 'OrRd_r', 'Oranges_r', 'PRGn_r', 'PiYG_r', 'PuBu_r', 'PuBuGn_r', 'PuOr_r', 'PuRd_r', 'Purples_r', 'RdBu_r', 'RdGy_r', 'RdPu_r', 'RdYlBu_r', 'RdYlGn_r', 'Reds_r', 'Spectral_r', 'Wistia_r', 'YlGn_r', 'YlGnBu_r', 'YlOrBr_r', 'YlOrRd_r', 'afmhot_r', 'autumn_r', 'binary_r', 'bone_r', 'brg_r', 'bwr_r', 'cool_r', 'coolwarm_r', 'copper_r', 'cubehelix_r', 'flag_r', 'gist_earth_r', 'gist_gray_r', 'gist_heat_r', 'gist_ncar_r', 'gist_rainbow_r', 'gist_stern_r', 'gist_yarg_r', 'gnuplot_r', 'gnuplot2_r', 'gray_r', 'hot_r', 'hsv_r', 'jet_r', 'nipy_spectral_r', 'ocean_r', 'pink_r', 'prism_r', 'rainbow_r', 'seismic_r', 'spring_r', 'summer_r', 'terrain_r', 'winter_r', 'Accent_r', 'Dark2_r', 'Paired_r', 'Pastel1_r', 'Pastel2_r', 'Set1_r', 'Set2_r', 'Set3_r', 'tab10_r', 'tab20_r', 'tab20b_r', 'tab20c_r', 'rocket', 'rocket_r', 'mako', 'mako_r', 'icefire', 'icefire_r', 'vlag', 'vlag_r', 'flare', 'flare_r', 'crest', 'crest_r'] ``` ``` python= sns.heatmap(top3_data.corr(), cmap= "coolwarm", annot=True) plt.show() ``` > Output: <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/051/118/original/12.png?1695826872" width="400" height="300">

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully