Plot Histograms and Box Plots from a Pandas DataFrame

Draw histograms and box plots straight from a DataFrame with df.hist(), df.plot.hist(), df.boxplot(), and df.plot.box(), including one chart per group.

To plot a histogram from a pandas DataFrame, call df["column"].plot.hist() for one column or df.hist() for a grid with every numeric column. For box plots, use df.boxplot(column="value", by="group") to get one box per group.

Quick Example

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

rng = np.random.default_rng(131)

# 600 meal deliveries by three kinds of courier.
vehicle = rng.choice(["Bike", "Scooter", "Car"], size=600, p=[0.45, 0.35, 0.20])
distance = rng.gamma(3.0, 1.0, size=600).round(1)
minutes_per_km = pd.Series(vehicle).map({"Bike": 4.6, "Scooter": 3.2, "Car": 2.6})
prep = pd.Series(vehicle).map({"Bike": 9, "Scooter": 11, "Car": 16})
minutes = (prep + minutes_per_km * distance + rng.gamma(2.0, 2.5, size=600)).round(1)

df = pd.DataFrame({"vehicle": vehicle, "distance_km": distance, "minutes": minutes,
                   "tip": rng.gamma(2.0, 1.4, size=600).round(2)})

fig, (left, right) = plt.subplots(1, 2, figsize=(9, 3.8))

df["minutes"].plot.hist(ax=left, bins=25, color="#2a9d8f", edgecolor="white")
left.set_xlabel("Delivery time (minutes)")
left.set_title("All Deliveries")

df.boxplot(column="minutes", by="vehicle", ax=right, grid=False)
right.set_title("By Vehicle")
right.set_xlabel("")
right.set_ylabel("Minutes")

fig.suptitle("")  # remove the "Boxplot grouped by vehicle" heading
fig.tight_layout()
plt.show()

Histogram of 600 delivery times beside box plots of delivery time for bikes, cars, and scooters

The made-up data has 600 deliveries. The code targets pandas 3 and Matplotlib 3.11; pandas draws these charts with Matplotlib, so any Matplotlib method works on the result.

Which pandas method should I use?

Method What it draws
df["col"].plot.hist() One histogram on one Axes
df.plot.hist() Several columns overlaid on one Axes, with shared bins
df.hist() A grid with one histogram per column
df.plot.box() One box per column
df.boxplot(by="group") One box per group

Histogram of Every Column with df.hist()

df.hist() draws one subplot for each numeric column and skips text columns. Set the grid shape with layout=(rows, columns).

df.hist(bins=20, layout=(1, 3), figsize=(9, 3.2), color="#457b9d",
        edgecolor="white", grid=False)
plt.tight_layout()
plt.show()

Three histograms, one each for distance, delivery minutes, and tip, all skewed to the right

All three columns lean right: most values are small, with a long tail of larger ones. df.hist() also plots datetime columns, so pass column=["minutes", "tip"] when you only want some of them.

Set the Bins

bins takes a number of bins or a list of edges. Explicit edges give round widths that are easy to describe.

ax = df["minutes"].plot.hist(bins=range(10, 76, 5), figsize=(7, 3.8),
                             color="#e76f51", edgecolor="white")
ax.set_xlabel("Delivery time (minutes)")
ax.set_ylabel("Deliveries")
ax.set_title("Delivery Times in 5-Minute Bins")
plt.show()

Histogram of delivery times in five-minute bins

Values outside the edges are left out without a warning, so check df["minutes"].min() and .max() first. The default is 10 bins.

One Histogram per Group

Pass by to split a column into one subplot per group. sharex and sharey keep the panels comparable.

df.hist(column="minutes", by="vehicle", bins=range(10, 76, 5), layout=(1, 3),
        figsize=(9, 3.2), sharex=True, sharey=True, color="#6d597a",
        edgecolor="white", grid=False, xrot=0)
plt.tight_layout()
plt.show()

Delivery time histograms for bike, car, and scooter in three panels with shared axes

Overlay Histograms of Several Groups

df.plot.hist() overlays columns, so first spread the groups into columns with pivot(). Each row then has a value in one column and NaN in the others, and pandas ignores the missing values.

wide = df.pivot(columns="vehicle", values="minutes")

ax = wide[["Bike", "Scooter", "Car"]].plot.hist(
    bins=range(10, 76, 5), alpha=0.55, density=True, figsize=(7, 4),
    color=["#264653", "#e9c46a", "#e76f51"])
ax.set_xlabel("Delivery time (minutes)")
ax.set_ylabel("Density")
ax.set_title("Delivery Times by Vehicle")
ax.legend(title="")
plt.show()

Overlaid semi-transparent histograms of delivery time for bike, scooter, and car

density=True scales each group to a total area of 1. Without it, cars would look small mostly because there are fewer of them. For smooth curves in place of bars, use wide.plot.kde(), which needs SciPy.

Box Plot of DataFrame Columns

df.plot.box() draws one box per numeric column. Pick columns that share a unit, or the larger one flattens the rest.

stages = pd.DataFrame({
    "Kitchen": rng.gamma(9.0, 1.3, size=300),
    "Waiting": rng.gamma(2.0, 2.0, size=300),
    "Travel": rng.gamma(5.0, 3.0, size=300),
})

ax = stages.plot.box(figsize=(7, 4))
ax.set_ylabel("Minutes")
ax.set_title("Time Spent in Each Stage")
plt.show()

Box plots of kitchen, waiting, and travel minutes with outliers above each box

The line in each box is the median, the box spans the middle half of the values, and the points beyond the whiskers are outliers. The Matplotlib box plot guide explains each part.

Box Plot Grouped by a Column

df.boxplot() with by groups the rows. Groups appear in alphabetical order; make the column an ordered categorical to choose the order. A list in column gives one subplot per value column.

df["vehicle"] = pd.Categorical(df["vehicle"], ["Bike", "Scooter", "Car"], ordered=True)

axes = df.boxplot(column=["minutes", "distance_km"], by="vehicle",
                  figsize=(8.5, 3.8), grid=False, sharey=False)
axes[0].set_title("Delivery time (minutes)")
axes[1].set_title("Distance (km)")
for ax in axes:
    ax.set_xlabel("")
axes[0].figure.suptitle("")
plt.tight_layout()
plt.show()

Two panels of box plots showing minutes and distance for bikes, scooters, and cars in that order

Distance looks similar for all three vehicles, but bikes have the longest tail of delivery times, up to 66 minutes against 53 for cars. In this made-up data, bikes are the slowest, so long trips cost them the most.

Change Box Plot Colors

color takes a dictionary with one entry per part of the plot, and patch_artist=True fills the boxes with the boxes color.

ax = stages.plot.box(
    figsize=(7, 4), patch_artist=True, widths=0.55,
    color={"boxes": "#a8dadc", "whiskers": "#1d3557",
           "medians": "#e63946", "caps": "#1d3557"},
    flierprops={"marker": ".", "markeredgecolor": "#1d3557"})
ax.set_ylabel("Minutes")
ax.set_title("Time Spent in Each Stage")
plt.show()

Box plots with light blue boxes, dark blue whiskers, and red median lines

If you also pass boxprops, whiskerprops, medianprops, or capprops, pandas ignores that part's entry in color. Put the color in the same dictionary, as in medianprops={"color": "#e63946", "linewidth": 2.5}.

Horizontal Box Plot

In pandas 3.0.5 with Matplotlib 3.11, passing orientation="horizontal" to a pandas box plot turns the boxes but puts the column names on the wrong axis. The older vert=False labels correctly but raises a deprecation warning. Calling Matplotlib's boxplot() avoids both.

fig, ax = plt.subplots(figsize=(7, 3.6))
ax.boxplot(stages, tick_labels=stages.columns, orientation="horizontal")
ax.invert_yaxis()  # first column at the top
ax.set_xlabel("Minutes")
ax.set_title("Time Spent in Each Stage")
plt.show()

Horizontal box plots of kitchen, waiting, and travel minutes

Unlike pandas, ax.boxplot() doesn't skip missing values: a column containing NaN gets an empty box. Pass [stages[c].dropna() for c in stages] as the data if you have gaps.

Practical Tips

  • df.hist() and df.boxplot() draw a grid by default. Turn it off with grid=False.
  • df.hist() returns a NumPy array of Axes, even for one column. Use axes.flat to loop over them.
  • The by argument of df.boxplot() adds a figure heading. Clear it with fig.suptitle("").
  • For a few dozen values or fewer, a raincloud plot or a plot of the raw points shows more than a box.

Similar Topics