0
0
Pandasdata~5 mins

Box plots in Pandas

Choose your learning style9 modes available
Introduction

A box plot helps you see how data is spread out and if there are any unusual values.

To compare test scores of students in different classes.
To check the spread of daily temperatures over a month.
To find outliers in sales data for different products.
To summarize the distribution of heights in a group of people.
Syntax
Pandas
DataFrame.boxplot(column=None, by=None, grid=True, figsize=None, fontsize=None, rot=0, return_type=None, ax=None, **kwargs)

column selects which data column to plot.

by groups data by a column to make multiple box plots.

Examples
Draws a box plot for the 'Age' column.
Pandas
df.boxplot(column='Age')
Draws box plots of 'Salary' grouped by 'Department'.
Pandas
df.boxplot(column='Salary', by='Department')
Draws box plots for all numeric columns with a custom size and no grid.
Pandas
df.boxplot(figsize=(8,6), grid=False)
Sample Program

This code creates a small table with departments, salaries, and ages. It then draws box plots to compare salaries in each department. The plot shows the spread and any unusual salary values.

Pandas
import pandas as pd
import matplotlib.pyplot as plt

data = {'Department': ['HR', 'HR', 'IT', 'IT', 'Sales', 'Sales'],
        'Salary': [50000, 52000, 60000, 61000, 45000, 47000],
        'Age': [25, 28, 30, 35, 22, 24]}
df = pd.DataFrame(data)

# Draw box plots of Salary grouped by Department
df.boxplot(column='Salary', by='Department', grid=False, figsize=(6,4))
plt.suptitle('')  # Remove automatic title
plt.title('Salary Distribution by Department')
plt.ylabel('Salary')
plt.show()
OutputSuccess
Important Notes

Box plots show median, quartiles, and possible outliers.

Use plt.show() to display the plot when using pandas with matplotlib.

Grouping by a column helps compare different categories side by side.

Summary

Box plots help visualize data spread and outliers.

Use DataFrame.boxplot() to create box plots in pandas.

Grouping data by a column shows comparisons between groups.