Cara menggunakan correlation matrix python

In this short guide, I’ll show you how to create a Correlation Matrix using Pandas. I’ll also review the steps to display the matrix using Seaborn and Matplotlib.

To start, here is a template that you can apply in order to create a correlation matrix using pandas:

df.corr()

Next, I’ll show you an example with the steps to create a correlation matrix for a given dataset.

Step 1: Collect the Data

Firstly, collect the data that will be used for the correlation matrix.

For example, I collected the following data about 3 variables:

A B C
45 38 10
37 31 15
42 26 17
35 28 21
39 33 12

Step 2: Create a DataFrame using Pandas

Next, create a DataFrame in order to capture the above dataset in Python:

import pandas as pd

data = {'A': [45,37,42,35,39],
        'B': [38,31,26,28,33],
        'C': [10,15,17,21,12]
        }

df = pd.DataFrame(data,columns=['A','B','C'])
print (df)

Once you run the code, you’ll get the following DataFrame:

Cara menggunakan correlation matrix python

Step 3: Create a Correlation Matrix using Pandas

Now, create a correlation matrix using this template:

df.corr()

This is the complete Python code that you can use to create the correlation matrix for our example:

import pandas as pd

data = {'A': [45,37,42,35,39],
        'B': [38,31,26,28,33],
        'C': [10,15,17,21,12]
        }

df = pd.DataFrame(data,columns=['A','B','C'])

corrMatrix = df.corr()
print (corrMatrix)

Run the code in Python, and you’ll get the following matrix:

Cara menggunakan correlation matrix python

Step 4 (optional): Get a Visual Representation of the Correlation Matrix using Seaborn and Matplotlib

You can use the seaborn and matplotlib packages in order to get a visual representation of the correlation matrix.

First import the seaborn and matplotlib packages:

import seaborn as sn
import matplotlib.pyplot as plt

Then, add the following syntax at the bottom of the code:

sn.heatmap(corrMatrix, annot=True)
plt.show()

So the complete Python code would look like this:

import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt

data = {'A': [45,37,42,35,39],
        'B': [38,31,26,28,33],
        'C': [10,15,17,21,12]
        }

df = pd.DataFrame(data,columns=['A','B','C'])

corrMatrix = df.corr()
sn.heatmap(corrMatrix, annot=True)
plt.show()

Run the code, and you’ll get the following correlation matrix:

Cara menggunakan correlation matrix python

That’s it! You may also want to review the following source that explains the steps to create a Confusion Matrix using Python. Alternatively, you may check this guide about creating a Covariance Matrix in Python.

Matrixplot adalah plot yang berbentuk matrix umumnya digunakan untuk melihat korelasi antar variabel

Untuk menggunakan matrixplot() pertama kita harus cari korelasi antar atribut data dengan fungsi corr()

dari hasil korelasi kita dapat membuat matrixplot untuk melihat data lebih dalam misalnya korelasi bisa dilihat dari perbedaan atau kedalaman warna

untuk dataset kita gunakan dataset tips

tips = sns.load_dataset('tips')
tips_corr = tips.corr()
tips_corr

Hasil korelasinya adalah

Cara menggunakan correlation matrix python

Hubungan ketiga atribut ini cukup tinggi. korelasi atribut tip dengan total_bill adalah 0.67 dan dengan atribut size adalah 0.48

Gunakan fungsi heatmap() untuk membuat matrixplot

Cara menggunakan correlation matrix python

Kita bisa gunakan argumen annot=True untuk menampilkan korelasi antar atribut. Jika nilai korelasi mendekati 1 maka hubungan antar atribut semakin tinggi

Cara menggunakan correlation matrix python

Kita juga bisa merubah warna korelasi dari matrixplot dengan mengubah argumen cmap

Kita bisa ubah argumen cmap menjadi YlGnBu, coolwarm, magma

Cara menggunakan correlation matrix python
Cara menggunakan correlation matrix python
Cara menggunakan correlation matrix python

Custom Pallate

Kita juga bisa gunakan light_palette() atau dark_palette() untuk merubah matrixplot menjadi 1 warna yang mempunyai gradasi warna

Kita cukup masukkan parameter warna di dalam fungsi light_palette() atau dark_palette()

Kita lihat gradasi warna dengan palplot()

sns.palplot(sns.light_palette("green"))
sns.palplot(sns.light_palette("blue"))
sns.palplot(sns.light_palette("yellow"))
sns.palplot(sns.light_palette("pink"))
sns.palplot(sns.light_palette("red"))

Hasilnya adalah

Cara menggunakan correlation matrix python

Sekarang kita akan coba implementasikan di dataset tips

warna = sns.light_palette("green")
sns.heatmap(tips_corr, annot=True, cmap=warna)

Cara menggunakan correlation matrix python

warna = sns.dark_palette("red")
sns.heatmap(tips_corr, annot=True, cmap=warna)

Cara menggunakan correlation matrix python

Oke.. berakhir sudah perjalanan seaborn.. selamat bereksplorasi lebih lanjut

Post navigation