How to Visualize Skewness and Kurtosis in Python

How to Visualize Skewness and Kurtosis in Python
Image by Editor | ChatGPT

Skewness and kurtosis are important statistical measures, helping to sescribe the shape of a data distribution. Visualizing these metrics helps in understanding data patterns. In Python, we can use libraries like matplotlib, seaborn, and scipy to create these visualizations.

In this article, you will learn how to visualize skewness and kurtosis using Python.

What Are Skewness and Kurtosis?

Skewness shows the asymmetry of a data distribution. It shows whether the leans more to the left or right of the average.

Type Skewness Value Description
Symmetric 0 Normal distribution
Positive > 0 Right-skewed (tail on the right)
Negative < 0 Left-skewed (tail on the left)

Kurtosis measures the tailedness or peakedness of a data distribution. It shows how heavy or light the tails of the distribution are compared to a normal distribution.

Type Excess Kurtosis Description
Mesokurtic 0 Normal peak
Leptokurtic > 0 High peak, heavy tails
Platykurtic < 0 Flat peak, light tails

Setting Up the Environment

Install required packages if you haven’t already:

pip install numpy pandas matplotlib seaborn scipy plotly

Then, import the necessary libraries:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import skew, kurtosis, probplot

Loading the Dataset

We’ll use Seaborn’s built-in tips dataset, which contains data about restaurant bills, tips, and other variables.

# Load Seaborn's built-in "tips" dataset
df = sns.load_dataset('tips')

# Display the first 5 rows
df.head()
   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

We will use the total_bill feature to visualize skewness and kurtosis.

Calculating Skewness and Kurtosis

Now, compute both skewness and excess kurtosis for each numeric column. Here’s how you can use scipy.stats to calculate both measures:

# Select the total_bill column
total_bill = df['total_bill']

# Calculate skewness and kurtosis
summary = pd.DataFrame({
    'Skewness': [skew(total_bill)],
    'Excess Kurtosis': [kurtosis(total_bill)]
}, index=['total_bill'])

summary
	      Skewness	Excess Kurtosis
total_bill    1.126235	   1.169168

Histogram with KDE

A histogram with KDE combines a bar chart and a smooth density curve. The histogram shows the frequency of data in bins, while the KDE curve overlays a smooth estimate of the data’s distribution. Skewness is visible if the KDE curve leans to one side. Kurtosis is reflected in how sharp or flat the KDE peak is.

# Plot histogram with KDE
plt.figure(figsize=(8, 5))
sns.histplot(total_bill, kde=True, bins=30, color='skyblue')
plt.title(f'Histogram with KDE')
plt.xlabel('total_bill')
plt.ylabel('Frequency')
plt.grid(True)
plt.show()

histogram

Box Plot

A box plot summarizes data using the median, quartiles, and potential outliers. Skewness is shown if the median line is closer to one end of the box or if one whisker is much longer than the other.

# Plot box plot
plt.figure(figsize=(8, 4))
sns.boxplot(x=total_bill, color='lightgreen')
plt.title('Box Plot')
plt.xlabel('total_bill')
plt.grid(True)
plt.show()

Box_plot

Q-Q Plot

A Q-Q plot compares the quantiles of your data against a normal distribution. If the points form a straight line, the data is normally distributed. A curved pattern suggests skewness, while points that diverge at the ends show higher or lower kurtosis.

# Q-Q plot to check normality
plt.figure(figsize=(6, 6))
probplot(total_bill, dist="norm", plot=plt)
plt.title('Q-Q Plot')
plt.grid(True)
plt.show()

Q-Q_plot

Summary Bar Plot

A summary bar plot displays summary statistics such as skewness and kurtosis as bars. Each bar represents a different metric or variable. It’s a compact way to visualize distribution characteristics numerically.

# Bar chart comparing skewness and kurtosis
summary.plot(kind='bar', figsize=(10, 5), title='Skewness and Kurtosis Overview')
plt.axhline(y=0, color='black', linestyle='--')
plt.ylabel('Value')
plt.grid(True)
plt.show()

bar_plot

Wrapping Up

Skewness tells us if the data is symmetric or leans to one side. Kurtosis shows how heavy or light the tails of the distribution are. Calculating these helps us understand the data shape and distribution.

Visual tools such as histograms, box plots, and Q-Q plots can help confirm these insights. This understanding is important for accurate data analysis and modeling.

Leave a Reply

Your email address will not be published. Required fields are marked *