How to Modify the X-Axis Range in Pandas Histogram


You can use the range argument to modify the x-axis range in a pandas histogram:

plt.hist(df['var1'], range=[10, 30])

In this particular example, we set the x-axis to range from 10 to 30.

The following example shows how to use the range argument in practice.

Example: Modifying the X-Axis Range in Pandas Histogram

Suppose we have the following pandas DataFrame:

import pandas as pd
import numpy as np

#make this example reproducible
np.random.seed(1)

#create DataFrame
df = pd.DataFrame({'team': np.repeat(['A', 'B', 'C'], 100),
                   'points': np.random.normal(loc=20, scale=2, size=300)})

#view head of DataFrame
print(df.head())

  team     points
0    A  23.248691
1    A  18.776487
2    A  18.943656
3    A  17.854063
4    A  21.730815

If we create a histogram for the points variable, pandas will automatically choose the range for the x-axis based on the minimum and maximum values of the points variable:

import matplotlib.pyplot as plt

#create histogram for points variable
plt.hist(df['points'], edgecolor='black')

The x-axis ranges from 14 to 25.

We can use the describe() function to view the minimum and maximum values for the points variable:

#summarize distribution of points variable
df['points'].describe()

count    300.000000
mean      20.148800
std        1.890841
min       14.413830
25%       18.818254
50%       20.176352
75%       21.372843
max       25.056651
Name: points, dtype: float64

We can see that the minimum value is 14.41 and the maximum value is 25.06, which explains why the x-axis in the plot currently ranges from 14 to 25.

However, we can use the range argument to force the x-axis to range from 10 to 30 instead:

import matplotlib.pyplot as plt

#create histogram for points variable with custom x-axis range
plt.hist(df['points'], edgecolor='black', range=[10, 30])

Notice that the x-axis now ranges from 10 to 30.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

How to Create a Histogram from Pandas DataFrame
How to Create a Histogram from a Pandas Series
How to Plot Histograms by Group in Pandas

Leave a Reply

Your email address will not be published.