In pandas, why do df.plot.hist() and df.hist() draw the same price and quantity columns so differently, and what does each return?
answer
- one panel versus a grid
- who computes the bin edges
- pooled range across columns
- Axes versus an array of Axes
basics
~20 sdf.plot.hist() overlays all numeric columns on one Axes with bin edges computed from every column pooled, so a narrow column collapses into a bin or two. df.hist() bins each column in its own subplot and returns an array of Axes.
solid answer
~40 s`df.plot.hist()` (same as `df.plot(kind="hist")`) draws all numeric columns on **one** Axes and computes one set of bin edges from the values of every column pooled together. If `price` runs from 5 to 20 and `qty` from 0 to 200, the default 10 bins are about 20 wide and almost every price lands in the first one. `subplots=True` splits the panels but keeps the shared edges. `df.hist()` is a separate method: it draws a grid with one subplot per numeric or datetime column, each with its own 10 bins, and returns a 2-D NumPy array of Axes. On a Series, both `s.hist()` and `s.plot.hist()` return a single Axes. The same pooling issue appears with `df.plot(kind="box")`, which puts every box on one shared y scale.
code
python · 15 linesimport numpy as np
import pandas as pd
rng = np.random.default_rng(0)
orders = pd.DataFrame(
{"price": rng.uniform(5, 20, 500), "qty": rng.integers(0, 200, 500)}
)
ax = orders.plot.hist() # one Axes, edges from both columns pooled
widths = {round(float(p.get_width()), 1) for p in ax.patches}
print(type(ax).__name__, widths)
grid = orders.hist() # one subplot per column, own edges
print(type(grid).__name__, grid.shape)
print([sorted({round(float(p.get_width()), 1) for p in a.patches}) for a in grid.ravel()])go deeper
Remember there are two histogram calls on a DataFrame: plot.hist overlays on one Axes, hist draws a grid of subplots.
Explain that plot.hist pools all columns to compute one set of bin edges, that subplots=True keeps them shared, and that df.hist returns a 2-D array of Axes.
When a quick-look histogram shows one column as a single spike, check for pooled bins and mismatched ranges before suspecting the data, and pick the call per comparison.
Nothing here needs a team policy; at most, review notebooks for overlaid histograms of columns on unrelated scales before their charts reach a decision deck.
## Two histogram methods that look alike pandas has two separate entry points that both draw histograms of a DataFrame: - **`DataFrame.plot.hist()`**, also spelled `df.plot(kind="hist")`, part of the plotting accessor; - **`DataFrame.hist()`**, an older method that predates the accessor and is still supported. They are not aliases. They differ in how many panels they draw, who decides the bin edges and what they return, and the difference shows the moment two columns have different ranges, such as a `price` column between 5 and 20 and a `qty` column between 0 and 200. | | `df.plot.hist()` | `df.hist()` | |---|---|---| | Panels | one Axes, columns overlaid | one subplot per column, in a grid | | Bin edges | computed once from all columns pooled | computed per column | | Default bins | 10 | 10 | | Columns used | numeric | numeric and datetime | | Returns | a Matplotlib `Axes` | a 2-D NumPy array of `Axes` | ## Why the overlay squashes a column `plot.hist` builds its bin edges once, from every non-missing value of every numeric column flattened into one array. With `bins=10` and values from 5 to 200, each bin is about 20 wide. The price column, which spans 15 units, falls into the first one or two bins, and the chart shows a single tall bar for price next to a spread-out quantity histogram. Nothing is wrong with the data; the two columns simply share one ruler. Points to know about this behaviour: - **`subplots=True` does not fix it.** `df.plot.hist(subplots=True)` gives one panel per column, but the bin edges are still computed from the pooled values. - **`bins=` raises the count for everyone.** More bins narrows each one, but the narrow column still gets a small share of them. - **`alpha=0.5`** makes overlaid columns readable when their ranges are similar; it does nothing for the range problem. - **`stacked=True`** stacks the columns' counts in each shared bin instead of overlaying them. ## How `df.hist()` differs `df.hist()` selects the numeric and datetime columns, creates one subplot per column with `squeeze=False`, and calls the histogram on each column separately with its own bins (10 by default). Each panel is titled with the column name. Because the result is built for a grid, the return value is a **2-D array of Axes**, even for two columns, where its shape is `(1, 2)`. If no numeric or datetime column is left, it raises `ValueError: hist method requires numerical or datetime columns, nothing to plot.` On a **Series**, both `s.hist()` and `s.plot.hist()` draw one histogram and return a single `Axes`, so the difference only bites on a DataFrame. ## Box plots share the same trap `df.plot(kind="box")` (or `df.plot.box()`) draws one box per numeric column on **one** Axes with one y scale, so a narrow column becomes a flat line next to a wide one. `df.boxplot()` is the older method; it returns an Axes by default (`return_type="axes"`) and, with `by="region"`, draws one panel per column with one box per group. `return_type="dict"` returns the Matplotlib artists instead, for styling individual boxes. ## Splitting one column by group Both histogram methods take `by=` to draw one panel per group of a categorical column, and here too the return types differ: - `df.plot.hist(column="price", by="region")` returns a **1-D** NumPy array of Axes, one per region; - `df.hist(column="price", by="region")` returns a **2-D** grid of Axes; - `df.boxplot(column="price", by="region")` returns a single Axes with one box per region, which is often the most compact comparison. Code that loops over the result therefore needs `.ravel()` (or `.flat`) for `df.hist`, while the 1-D array from `plot.hist` can be iterated directly. With `by=`, `plot.hist` computes bins per panel rather than pooled across groups, so the squashing problem described above comes from mixing columns, not from mixing groups. ## Choosing the call 1. Comparing the **shapes** of columns with different ranges: `df.hist()`, or loop over the columns with `df[col].plot.hist()`. 2. Comparing columns on the **same scale** (two price lists in one currency): `df.plot.hist(alpha=0.5)` on one Axes. 3. Splitting one column by group: `df.plot.hist(column="price", by="region")` or `df.boxplot(column="price", by="region")`. Whether a histogram's bucket width is telling the truth about a distribution is a chart-reading question covered separately; this lesson is about which pandas call computes the buckets.
- Does df.plot.hist(subplots=True) give each column its own bins?No. It draws one panel per column, but the bin edges are still computed once from all numeric columns pooled, so a narrow column stays squashed into a bin or two. Use `df.hist()` or plot each column with its own `plot.hist()` call when ranges differ.
- How do you get one price histogram per region in pandas?`df.plot.hist(column="price", by="region")` draws one panel per region and returns an array of Axes; `df.hist(column="price", by="region")` does the same with the older method. For a compact comparison, `df.boxplot(column="price", by="region")` puts one box per region on a single panel.
plot.hist is like weighing a mouse and an elephant on one truck scale: the reading is correct, but the mouse barely moves the needle. df.hist gives each animal its own scale.
- df.hist() is just an alias of df.plot.hist()
- subplots=True gives every column its own bin edges
- plot.hist computes separate bins for each column
- df.hist() returns a single Axes like df.plot()
- A squashed histogram means the data was corrupted on load