plt.boxplot() summarises a numeric variable's distribution in five numbers at a glance: minimum, first quartile, median, third quartile, and maximum.
A Basic Box Plot
R Code
scores = [55,60,62,65,70,72,75,95] plt.boxplot(scores) plt.title("Exam Scores") plt.show()
Comparing Groups
R Code
group_a = [55,60,65] group_b = [80,85,90] plt.boxplot([group_a, group_b], labels=["Group A", "Group B"]) plt.title("Score by Group") plt.show()
The Easier Way with Seaborn and a DataFrame
R Code
import pandas as pd import seaborn as sns df = pd.DataFrame({ "score": [55,60,65, 80,85,90], "group": ["A","A","A", "B","B","B"] }) sns.boxplot(data=df, x="group", y="score") plt.show()
Advanced: Extracting the Actual Statistics
🚀 Advanced Example
The dictionary returned by plt.boxplot() contains the exact numbers used to draw it - useful for reporting values rather than just eyeballing the chart.R Code
result = plt.boxplot(scores) print([item.get_ydata() for item in result["whiskers"]])
Key Points
- plt.boxplot(data) draws the five-number summary; pass a list of lists to compare groups.
- seaborn.boxplot(data=df, x=..., y=...) is the more convenient option when working with a DataFrame.
- Points beyond the whiskers are potential outliers, drawn individually.