Introduction

Before getting into the details and visualizing different forms of data, let's first take the initial steps and know about the building blocks which will facilitate the understanding of data visualization better.

So as part of the building blocks, we will be going through some basic operations with different python libraries which give us a good foundation, so that we could build our knowledge of visualization on top of it.

NumPy

NumPy is the fundamental package for scientific computing with Python. It contains among other things:

  • a powerful N-dimensional array object
  • sophisticated (broadcasting) functions
  • tools for integrating C/C++ and Fortran code
  • useful linear algebra, Fourier transform, and random number capabilities
In [1]:
import numpy as np

1. Creating a 3X1 numpy array

In [10]:
a = np.array([3,4,3])
print(type(a))
print("The shape of a: ",a.shape)
print(a[0],a[1],a[2])
<class 'numpy.ndarray'>
The shape of a:  (3,)
3 4 3

2. Creating a 2X2 numpy array

In [11]:
b = np.array([[3,4],[5,6]])
print(type(b))
print("The shape of b: ",b.shape)
print(b[0,0],b[0,1],b[1,0],b[1,1])
<class 'numpy.ndarray'>
The shape of b:  (2, 2)
3 4 5 6

3. Creating a 3X2 numpy array

In [12]:
c = np.array([[12,42],[43,15],[345,23]])
print(type(c))
print("The shape of c: ",c.shape)
print(c[0,0],c[0,1],c[1,0],c[1,1],c[2,0],c[2,1])
<class 'numpy.ndarray'>
The shape of c:  (3, 2)
12 42 43 15 345 23

4. Creating a 3X3 numpy array

In [13]:
d = np.array([[32,43,11],[11,44,12],[34,65,23]])
print(type(d))
print("The shape of d: ",d.shape)
print(d[0,0],d[0,1],d[0,2],d[1,0],d[1,1],d[1,2],d[2,0],d[2,1],d[2,2])
<class 'numpy.ndarray'>
The shape of d:  (3, 3)
32 43 11 11 44 12 34 65 23

5. Creating a 3X3X3 numpy array

In [23]:
e = np.array([[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]],[[19,20,21],[22,23,24],[25,26,27]]])
print(type(e))
print("The shape of e: ",e.shape)
print(e)
<class 'numpy.ndarray'>
The shape of e:  (3, 3, 3)
[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]]

 [[10 11 12]
  [13 14 15]
  [16 17 18]]

 [[19 20 21]
  [22 23 24]
  [25 26 27]]]

6. Creating a 2X3 zero array

In [40]:
f = np.zeros((2,3))
print("The array f has 2 rows and 3 columns:\n",f)
The array f has 2 rows and 3 columns:
 [[0. 0. 0.]
 [0. 0. 0.]]

7. Creating a 4X2 array of ones

In [39]:
g = np.ones((4,2))
print("The array g has 4 rows and 2 columns:\n",g)
The array g has 4 rows and 2 columns:
 [[1. 1.]
 [1. 1.]
 [1. 1.]
 [1. 1.]]

8. Creating a 2X2 constant array

In [38]:
h = np.full((2,2),9)
print("The constant array h:\n",h)
The constant array h:
 [[9 9]
 [9 9]]

9. Creating a random 3X3 array

In [41]:
i = np.random.random((3,3))
print("The random array i:\n",i)
The random array i:
 [[0.94588842 0.95943577 0.06415189]
 [0.04811429 0.70852042 0.77565052]
 [0.87805389 0.62794919 0.09636378]]

Array Indexing

In [50]:
#### Creating a 3X4 array

j = np.array([[1,2,3,4],[3,4,5,6],[23,43,11,5]])
print("The array has 3 rows and 4 columns:\n",j)
i = j[:2,1:4]
print("The value of the indexed j values are:\n",i)
The array has 3 rows and 4 columns:
 [[ 1  2  3  4]
 [ 3  4  5  6]
 [23 43 11  5]]
The value of the indexed j values are:
 [[2 3 4]
 [4 5 6]]

Now let's modify the sliced array i values and see if it affects the values in array j or not

In [52]:
print("the values of array j at 0th row and 1st column:\n",j[0,1])

## Modifying the sliced array i
i[0,0] =100

print("the values of array j at 0th row and 1st column:\n",j[0,1])
the values of array j at 0th row and 1st column:
 100
the values of array j at 0th row and 1st column:
 100

Datatypes in Arrays

In [57]:
## Integer datatype

j = np.array([1,2])
print("The datatype of j is:",j.dtype)

##Float Datatype

k = np.array([1.0,2.4])
print("The datatype of k is:",k.dtype)

## typecasting

l = np.array([1.0,2.0],dtype = np.int64)

print("The typecasted datatype of l:",l.dtype)
The datatype of j is: int32
The datatype of k is: float64
The typecasted datatype of l: int64

Element wise Arithmetic operation

In [58]:
X = np.array([[1,2,3,4],[3,5,6,1]])
Y = np.array([[4,5,1,9],[7,4,1,9]])

1. Element wise addition

In [60]:
print("The approach-1 for Element-wise addition is:\n",X + Y)
print("The approach-2 for Element-wise addition is :\n",np.add(X,Y))
The approach-1 for Element-wise addition is:
 [[ 5  7  4 13]
 [10  9  7 10]]
The approach-2 for Element-wise addition is :
 [[ 5  7  4 13]
 [10  9  7 10]]

2. Element-wise substraction

In [62]:
print("The approach-1 for Element-wise substraction is:\n",X - Y)
print("The approach-2 for Element-wise substraction is :\n",np.subtract(X,Y))
The approach-1 for Element-wise addition is:
 [[-3 -3  2 -5]
 [-4  1  5 -8]]
The approach-2 for Element-wise addition is :
 [[-3 -3  2 -5]
 [-4  1  5 -8]]

3. Element-wise product

In [63]:
print("The approach-1 for Element-wise product is:\n",X * Y)
print("The approach-2 for Element-wise product is :\n",np.multiply(X,Y))
The approach-1 for Element-wise addition is:
 [[ 4 10  3 36]
 [21 20  6  9]]
The approach-2 for Element-wise addition is :
 [[ 4 10  3 36]
 [21 20  6  9]]

4. Element wise division

In [64]:
print("The approach-1 for Element-wise division is:\n",X / Y)
print("The approach-2 for Element-wise division is :\n",np.divide(X,Y))
The approach-1 for Element-wise addition is:
 [[0.25       0.4        3.         0.44444444]
 [0.42857143 1.25       6.         0.11111111]]
The approach-2 for Element-wise addition is :
 [[0.25       0.4        3.         0.44444444]
 [0.42857143 1.25       6.         0.11111111]]

5. Element wise squareroot

In [65]:
print("The approach for Element-wise square-root is :\n",np.sqrt(X))
The approach-2 for Element-wise square-root is :
 [[1.         1.41421356 1.73205081 2.        ]
 [1.73205081 2.23606798 2.44948974 1.        ]]

6. Adding the elements column wise

In [67]:
x = np.array([[1,2],[3,4]])
print("The normal sum is:",np.sum(x))
print("The column wise addition is:",np.sum(x,axis = 0))
The normal sum is: 10
The column wise addition is: [4 6]

7. Adding row wise

In [68]:
x = np.array([[1,2],[3,4]])
print("The normal sum is:",np.sum(x))
print("The column wise addition is:",np.sum(x,axis = 1))
The normal sum is: 10
The column wise addition is: [3 7]

8. Computing mean

In [69]:
print("The overall mean is: ",np.mean(x))
print("The columnwise mean is: ",np.mean(x,axis=0))
print("The rowwise mean is: ",np.mean(x,axis=1))
The overall mean is:  2.5
The columnwise mean is:  [2. 3.]
The rowwise mean is:  [1.5 3.5]

SciPy

Numpy provides a high-performance multidimensional array and basic tools to compute with and manipulate these arrays. SciPy builds on this, and provides a large number of functions that operate on numpy arrays and are useful for different types of scientific and engineering applications.

For this course, we will primariyl be using the SciPy.Stats sub-library.

SciPy.Stats

The SciPy.Stats module contains a large number of probability distributions as well as a growing library of statistical functions such as:

  • Continuous and Discrete Distributions (i.e Normal, Uniform, Binomial, etc.)
  • Descriptive Statistcs
  • Statistical Tests (i.e T-Test)
In [70]:
from scipy import stats
import numpy as np

Printing Normal Random Variables

In [71]:
print(stats.norm.rvs(size = 15))
[-1.29499677 -0.22451311 -0.19765175  0.41810737  0.5816834  -0.17233972
  1.13211671 -1.5192908  -1.00744583 -0.75964961  0.28483644 -0.51279441
  1.12538249 -0.24824641  0.85651006]

MatPlotLib

Matplotlib is a plotting library. In this section give a brief introduction to the matplotlib.pyplot module.

In [107]:
import numpy as np
import matplotlib.pyplot as plt

1.Computing x and y coordinates for Sine curve

In [109]:
x = np.arange(0,3*np.pi,0.1)
print(x)
y = np.sin(x)
plt.plot(x,y)
plt.show()
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7
 1.8 1.9 2.  2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3.  3.1 3.2 3.3 3.4 3.5
 3.6 3.7 3.8 3.9 4.  4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 5.  5.1 5.2 5.3
 5.4 5.5 5.6 5.7 5.8 5.9 6.  6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 7.  7.1
 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 8.  8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9
 9.  9.1 9.2 9.3 9.4]

2. Computing the x and y coordinate for the sine and cosine curve

In [111]:
x = np.arange(0,3*np.pi,0.1)
y_sin = np.sin(x)
y_cosin = np.cos(x)

plt.plot(x,y_sin)
plt.plot(x,y_cosin)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sine and Cosine curve')
plt.legend(['Sine','Cosine'])
plt.show()

Subplots

In [112]:
import numpy as np
import matplotlib.pylab as plt

3.Computing the subplots

In [120]:
## Compute the x and y coordinate for sine and cosine curve

x = np.arange(0,4*np.pi,0.5)
y_sin = np.sin(x)
y_cos = np.cos(x)

## Let's set up a grid for making subplots within those grids with 2 rows and 3 columns.

plt.subplot(2,3,1)

## Lets make the first plot

plt.plot(x,y_sin)
plt.title("1st-sine curve")

plt.subplot(2,3,2)

## Lets make the 2nd plot

plt.plot(x,y_cos)
plt.title("2nd-cos curve")

plt.subplot(2,3,3)

## Lets make the third plot

plt.plot(x,y_sin)
plt.title("3rd-sine curve")

plt.subplots_adjust(top = 0.99, bottom=0.01, hspace=.5, wspace=0.4)

plt.subplot(2,3,4)

## Lets make the forth plot

plt.plot(x,y_cos)
plt.title("4th-sine curve")


plt.subplot(2,3,5)

## Lets make the fifth plot

plt.plot(x,y_sin)
plt.title("5th-sine curve")


plt.subplot(2,3,6)

## Lets make the sixth plot

plt.plot(x,y_sin)
plt.title("6th-sine curve")
Out[120]:
Text(0.5, 1.0, '6th-sine curve')

Seaborn

In [122]:
import seaborn as sns
import pandas as pd

1. Import data

In [123]:
df = pd.read_csv("Admission_Predict.csv")
df.head()
Out[123]:
Serial No. GRE Score TOEFL Score University Rating SOP LOR CGPA Research Chance of Admit
0 1 337 118 4 4.5 4.5 9.65 1 0.92
1 2 324 107 4 4.0 4.5 8.87 1 0.76
2 3 316 104 3 3.0 3.5 8.00 1 0.72
3 4 322 110 3 3.5 2.5 8.67 1 0.80
4 5 314 103 2 2.0 3.0 8.21 0 0.65
In [128]:
df['Chance of Admit '].unique()
Out[128]:
array([0.92, 0.76, 0.72, 0.8 , 0.65, 0.9 , 0.75, 0.68, 0.5 , 0.45, 0.52,
       0.84, 0.78, 0.62, 0.61, 0.54, 0.66, 0.63, 0.64, 0.7 , 0.94, 0.95,
       0.97, 0.44, 0.46, 0.74, 0.91, 0.88, 0.58, 0.48, 0.49, 0.53, 0.87,
       0.86, 0.89, 0.82, 0.56, 0.36, 0.42, 0.47, 0.55, 0.57, 0.96, 0.93,
       0.38, 0.34, 0.79, 0.71, 0.69, 0.59, 0.85, 0.77, 0.81, 0.83, 0.67,
       0.73, 0.6 , 0.43, 0.51, 0.39])

Scatter Plot

2. Creating a scatter plot with x-axis = 'GRE Score',y-axis = 'TOEFL Score'

In [125]:
sns.lmplot(x = 'GRE Score',y = 'TOEFL Score',data = df)

plt.show()

3.Scatter plot without the regression line and specifying legend as 'University Rating'

In [130]:
sns.lmplot(x='GRE Score',y='TOEFL Score',data=df,fit_reg=False,hue ='University Rating')
Out[130]:
<seaborn.axisgrid.FacetGrid at 0x1e7bf6b3088>

4. Simple scatter plot with 2 variables

In [275]:
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
ax = sns.scatterplot(x="total_bill", y="tip", data=tips)
In [277]:
tips
Out[277]:
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
... ... ... ... ... ... ... ...
239 29.03 5.92 Male No Sat Dinner 3
240 27.18 2.00 Female Yes Sat Dinner 2
241 22.67 2.00 Male Yes Sat Dinner 2
242 17.82 1.75 Male No Sat Dinner 2
243 18.78 3.00 Female No Thur Dinner 2

244 rows × 7 columns

In [266]:
sns.scatterplot(x='total_bill',y='tip',data = tips)
plt.show()

5. Grouping the data by a particular variable and plotting the scatter plot

In the below plot we use hue argument.

  1. hue is used for grouping variable that will produce points with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case. In our case we have used hue to group time by color.
In [268]:
sns.scatterplot(x="total_bill",y="tip",data = tips, hue='time')
plt.show()

6. Now let's group the data points by color and marker

Here we use:

  1. hue which will group the data with points having different colors
  2. style is used for grouping variable that will produce points with different markers. Can have a numeric dtype but will always be treated as categorical. Here in our case we have used style to group the "time" which will have different markers
In [272]:
sns.scatterplot(x="total_bill", y="tip",hue="time", style="time", data=tips)
plt.show()

7. Now let's vary the color and marker to show different grouping variables

In [274]:
sns.scatterplot(x="total_bill",y="tip",hue="day",style='time',data=tips)
plt.show()

8. Now let's show the scatter plot by plotting the data by size.

Let's first understand what is size.

size: It is basically grouping variable that will produce points with different sizes. Can be either categorical or numeric, although size mapping will behave differently in latter case.

In [278]:
sns.scatterplot(x='total_bill',y='tip',size='size',data=tips)
plt.show()
In [ ]:
sns.scatterplot(x='total_bill',y='tip',size=)

9. Now let's do some modification to the above scatter plot and assign hue ='size' to group the 'size by different color

In [313]:
cmap = sns.cubehelix_palette(dark=.1, light=.9, as_cmap=True)

sns.scatterplot(x="total_bill",y='tip',size='size',hue='size',palette=cmap,data=tips)
plt.show()

10. Now let's make a bit more modification and assign "sizes" values to the different "size" values(1,2,3,4,5,6) using sizes =(20,400).

That means, the smallest size 1 has the least size = 20 and the largest size 6 has the size =200.

Also we will make the sizes color vary with the smallest size having the lightest color and the largest size having the darkest color using the hue_norm = (0,7).

We also define the palette by using the below code:

cmap = sns.cubehelix_palette(dark=.1, light=.8, as_cmap=True) Based on the value of the dark and light argument of this function, we can vary the hue_norm values. The smaller the value of dark, the larger is the range for the hue_norm. This means if the dark = 0.1 then the range of hue_norm also increases.

Note: Also remember, we can use the sizes argument only when we specify the size argument.

In [364]:
cmap = sns.cubehelix_palette(dark=.1, light=.8, as_cmap=True)
sns.scatterplot(x="total_bill",y='tip',size='size',hue='size',sizes = (20,400),hue_norm=(0,8),
                palette=cmap,legend ='full',data=tips)
plt.show()

11. Now let's make some more modification and introduce a categorical value to 'size' instead of numerical value and also assign hue to a categorical variable 'day' and see how the plot looks

In [328]:
sns.scatterplot(x='total_bill',y='tip',hue='day',size='smoker',sizes = (40,200),palette='Set1',data=tips)
Out[328]:
<matplotlib.axes._subplots.AxesSubplot at 0x1e7c4a79088>

12. Let's change the markers in the plot for better understanding

Here we are using

  1. style which will group the data based on 'time' having different markers,
  2. hue which will group the data with points having different colors,
  3. markers for different types of representation,
  4. palette ="Set1" for a particular shade of color.
  5. size='time' is used to assign the sizes =(200,120) to the time variables (Lunch, Dinner)

Note: Also remember, we can use the sizes argument only when we specify the size argument.

In [349]:
markers = {"Lunch":'s',"Dinner":'X'}
sns.scatterplot(x="total_bill",y="tip",style='time',markers=markers,
                palette="Set1",data =tips,hue='time',size = 'time',sizes=(200,120))
Out[349]:
<matplotlib.axes._subplots.AxesSubplot at 0x1e7c9a48508>

13. Now instead of passing column names of the dataframe as the arguments, lets pass the vectors to the plot

In [351]:
iris = sns.load_dataset("iris")
sns.scatterplot(x=iris.sepal_length,y=iris.sepal_width,
               hue=iris.species,style=iris.species)

plt.show()

14. Now let's use relplot() to combine scatterplot() and FacetGrid: This allows grouping within additional categorical variables

In [355]:
sns.relplot(x="total_bill",y="tip",col="time",hue="day",style="day",
           kind="scatter",data = tips,size ="day",sizes=(80,200))
plt.show()
In [154]:
import pandas as pd

df = pd.read_csv("student.csv")
df.head()
Out[154]:
Student_id Age Gender Grade Employed
0 1 19 Male 1st Class yes
1 2 20 Female 2nd Class no
2 3 18 Male 1st Class no
3 4 21 Female 2nd Class no
4 5 19 Male 1st Class no
In [155]:
df['Age'].unique()
Out[155]:
array([19, 20, 18, 21, 22], dtype=int64)

4. Drawing a categorical scatterplot with non-overlapping points with x-axis='Gender',y-axis='Age'

In [195]:
sns.swarmplot(x='Gender',y='Age',data=df)

plt.show()

5. Fetching the data with Age >=19 and <22 and creating a categorical scatterplot with non-overlapping points with x-axis='Gender',y-axis='Age'

In [196]:
df1 = df[(df.Age >= 19) &(df.Age<22)]
In [197]:
df1.head()
Out[197]:
Student_id Age Gender Grade Employed
0 1 19 Male 1st Class yes
1 2 20 Female 2nd Class no
3 4 21 Female 2nd Class no
4 5 19 Male 1st Class no
5 6 20 Male 2nd Class yes
In [198]:
sns.swarmplot(x='Gender',y='Age',data=df1)
plt.show()

1.Import another dataset

In [174]:
data = pd.read_csv("Cartwheeldata.csv")
In [175]:
data.head()
Out[175]:
ID Age Gender GenderGroup Glasses GlassesGroup Height Wingspan CWDistance Complete CompleteGroup Score
0 1 56 F 1 Y 1 62.0 61.0 79 Y 1 7
1 2 26 F 1 Y 1 62.0 60.0 70 Y 1 8
2 3 33 F 1 Y 1 66.0 64.0 85 Y 1 7
3 4 39 F 1 N 0 64.0 63.0 87 Y 1 10
4 5 27 M 2 N 0 73.0 75.0 72 N 0 4

2. Grouping the swarms categorically by Gender

In [176]:
sns.swarmplot(x ='Gender',y='CWDistance',data=data)
Out[176]:
<matplotlib.axes._subplots.AxesSubplot at 0x1e7c3e69c48>

1. Importing the "tips" dataset to visualize using swarmplot

In [199]:
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.swarmplot(x=tips["total_bill"])

2. Grouping the swarms categorically by day

In [203]:
sns.swarmplot(x="day",y='total_bill',data= tips)

plt.show()

3. Now let's draw horizontal swarms by making the x-axis as total_bill and y-axis as day

In [204]:
sns.swarmplot(x='total_bill',y='day',data=tips)
plt.show()

4. Not let's go ahead a color the graph based on the 2nd categorical data column "sex"

In [245]:
sns.swarmplot(x="day",y="total_bill",hue='sex',data=tips)
plt.show()

5. Splitting the sub-levels of the hue variable along the categorical axis

Here using

  1. palette ='Set1' changes the color of the dots and
  2. dodge = True separates the categories
In [239]:
sns.swarmplot(x="day",y="total_bill",hue="smoker",data = tips, palette="Set1",dodge = True)
Out[239]:
<matplotlib.axes._subplots.AxesSubplot at 0x1e7c50c2788>

6. Plotting the swarm with x as time and y as tip

In [218]:
sns.swarmplot(x='time',y='tip',data=tips)
plt.show()

7. Now plotting the same as we did in point 6, but by explicitely specifying order with 'Dinner' first and 'Lunch' second

In [219]:
sns.swarmplot(x='time',y='tip',palette='Set1',order=['Dinner','Lunch'],data = tips)
plt.show()

8. Plotting using larger dots

In [223]:
sns.swarmplot(x='time',y='tip',palette='Set1',data=tips,size = 7)
plt.show()

9. Drawing swarm plots observation on top of boxplots to see how the data points are spread out.

If you notice here in the boxplot, the whis=np.inf ensures that the whisker of the boxplot extends till the last outlier. You can see that in the below plot the whicker connects to the last point which is the outlier where as this doesnot happen if we are not using whis=np.inf. This is evident in the plot no 10.

In [235]:
sns.boxplot(x='tip',y='day',data=tips,whis=np.inf)
sns.swarmplot(x='tip',y='day',data=tips,color=".1")
plt.show()

10. Plotting the box plot without the whis=np.inf. The difference is the whisker is not extended to the outlier as it happened above

In [236]:
sns.boxplot(x='tip',y='day',data=tips)
plt.show()

11. Using catplot() to combine a swarmplot() and a FacetGrid. This allows grouping within additional categorical variables

In [265]:
sns.catplot(x='sex',y ='total_bill',hue='smoker',col='time',data=tips,kind='swarm',height = 6, aspect=.8)
plt.show()

Boxplot

1. Let's draw a single horizontal boxplot with a single variable

In [366]:
import seaborn as sns
sns.set(style = "whitegrid")
tips = sns.load_dataset("tips")
sns.boxplot(x=tips["total_bill"])
plt.show()

2. Let's now draw a horizontal boxplot with categorical variables

In [367]:
sns.boxplot(x="day",y="total_bill",data = tips)
plt.show()

3. Now let's group the data by using using hue.

  1. hue will basically group the variable by producing points with different colors.
  2. palette = "Set1" changes the color of the categorical value
In [368]:
sns.boxplot(x="day",y="total_bill",hue="smoker",palette="Set1",data =tips)
plt.show()

4. Now let's do the grouping of categorical values when some bins don't any value

In [373]:
sns.boxplot(x="day",y="total_bill",hue="time",data =tips,linewidth=1)
plt.show()

5. Controlling the boxplot order by explicit ordering

In [374]:
sns.boxplot(x="time",y="tip",data=tips,order=['Dinner','Lunch'])
plt.show()

6. Now let's take a dataset which contains all the numerical columns and plot a boxplot for it

In [375]:
iris = sns.load_dataset("iris")
In [376]:
iris.head()
Out[376]:
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
In [377]:
sns.boxplot(data=iris,orient='h',palette='Set1')
plt.show()

7. Now let's say we want to check a condition in the dataset and then plot that.

Let's take such example where we want to check the total_bill based on the condition that the days are weekend.

In the below plot you can see that the data has been categorized as True ans False based on whether it is weekend or weekday

In [378]:
tips["weekend"] = tips["day"].isin(["Sat","Sun"])
sns.boxplot(x="day",y="total_bill",hue="weekend",data = tips)
plt.show()

8. Now let's use catplot() to combine a boxplot() and a FacetGrid. This allows grouping within additional categorical variables.

In [386]:
sns.catplot(x="sex",y="total_bill",hue="smoker",col="time",
            data = tips,kind="box",height = 7, aspect = .8)
plt.show()

9. Import a new dataset

In [387]:
data = pd.read_csv("Cartwheeldata.csv")
In [388]:
data.head()
Out[388]:
ID Age Gender GenderGroup Glasses GlassesGroup Height Wingspan CWDistance Complete CompleteGroup Score
0 1 56 F 1 Y 1 62.0 61.0 79 Y 1 7
1 2 26 F 1 Y 1 62.0 60.0 70 Y 1 8
2 3 33 F 1 Y 1 66.0 64.0 85 Y 1 7
3 4 39 F 1 N 0 64.0 63.0 87 Y 1 10
4 5 27 M 2 N 0 73.0 75.0 72 N 0 4

10. Plot a boxplot with the all the numerical columns

In [182]:
sns.boxplot(data = data.loc[:,["Age","Height","Wingspan","CWDistance","Score"]])
plt.show()

11. Plotting the boxplot for all numerical columns with criteria as Gender = "M"

In [184]:
sns.boxplot(data= data.loc[data['Gender']=='M',["Age","Height","Wingspan","CWDistance","Score"]])
plt.show()

12. Plotting the boxplot for all the numerical columns with criterial as Gender = "F"

In [185]:
sns.boxplot(data=data.loc[data['Gender']=='F',["Age","Height","Wingspan","CWDistance","Score"]])
plt.show()

13. Plotting the boxplot with 1 numerical column with criteria as Gender = M

In [187]:
sns.boxplot(data = data.loc[data['Gender']=='M',["Score"]])

plt.show()

14. Plotting the boxplot with 1 numerical column with criteria as Gender = F

In [188]:
sns.boxplot(data = data.loc[data['Gender']=='F',["Score"]])

plt.show()

Distance Plot

In [397]:
df = pd.read_csv("student.csv")
df.head()
Out[397]:
Student_id Age Gender Grade Employed
0 1 19 Male 1st Class yes
1 2 20 Female 2nd Class no
2 3 18 Male 1st Class no
3 4 21 Female 2nd Class no
4 5 19 Male 1st Class no

1. Draw a distribution graph for "Age"

In [189]:
## Distribution plot 
sns.distplot(df.Age)
plt.show()
In [398]:
data = pd.read_csv("Cartwheeldata.csv")
data.head()
Out[398]:
ID Age Gender GenderGroup Glasses GlassesGroup Height Wingspan CWDistance Complete CompleteGroup Score
0 1 56 F 1 Y 1 62.0 61.0 79 Y 1 7
1 2 26 F 1 Y 1 62.0 60.0 70 Y 1 8
2 3 33 F 1 Y 1 66.0 64.0 85 Y 1 7
3 4 39 F 1 N 0 64.0 63.0 87 Y 1 10
4 5 27 M 2 N 0 73.0 75.0 72 N 0 4

2. Draw a distribution graph for CWDistance

In [190]:
sns.distplot(data.CWDistance)
plt.show()

Count plot

In [393]:
df = pd.read_csv("student.csv")
df.head()
Out[393]:
Student_id Age Gender Grade Employed
0 1 19 Male 1st Class yes
1 2 20 Female 2nd Class no
2 3 18 Male 1st Class no
3 4 21 Female 2nd Class no
4 5 19 Male 1st Class no

1. Countplot to count the number of records for each gender

In [394]:
sns.countplot(x='Gender',data=df)
plt.xticks(rotation=45)
plt.show()

2. Countplot to count the number of records for each gender

In [395]:
data = pd.read_csv("Cartwheeldata.csv")
data.head()
Out[395]:
ID Age Gender GenderGroup Glasses GlassesGroup Height Wingspan CWDistance Complete CompleteGroup Score
0 1 56 F 1 Y 1 62.0 61.0 79 Y 1 7
1 2 26 F 1 Y 1 62.0 60.0 70 Y 1 8
2 3 33 F 1 Y 1 66.0 64.0 85 Y 1 7
3 4 39 F 1 N 0 64.0 63.0 87 Y 1 10
4 5 27 M 2 N 0 73.0 75.0 72 N 0 4
In [396]:
sns.countplot(x='Gender',data = data)
plt.xticks(rotation=0)
plt.show()
In [ ]: