---
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">