Automatically setting Y-axis limits for a bar graph using Matplotlib

Setting Y-axis limits for bar graphs helps improve visualization by focusing on the data range and removing unnecessary whitespace. Matplotlib provides the ylim() method to automatically calculate and set appropriate Y-axis boundaries.

Steps

  • Set the figure size and adjust the padding between and around the subplots.
  • Create two lists for data points.
  • Make two variables for max and min values for Y-axis.
  • Use ylim() method to limit the Y-axis range.
  • Use bar() method to plot the bars.
  • To display the figure, use show() method.

Example

Here's how to automatically set Y-axis limits based on your data range ?

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = [1, 2, 3, 4, 5]
y = [8, 4, 6, 1, 3]

max_y_lim = max(y) + 0.5
min_y_lim = min(y) - 0.5

plt.ylim(min_y_lim, max_y_lim)
plt.bar(x, y)
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.title('Bar Graph with Custom Y-axis Limits')
plt.show()

Alternative Approach Using Padding

You can also add percentage-based padding for more dynamic scaling ?

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [8, 4, 6, 1, 3]

# Add 10% padding to both ends
y_range = max(y) - min(y)
padding = y_range * 0.1

max_y_lim = max(y) + padding
min_y_lim = min(y) - padding

plt.figure(figsize=(8, 4))
plt.ylim(min_y_lim, max_y_lim)
plt.bar(x, y, color='skyblue', edgecolor='black')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Graph with Percentage-based Padding')
plt.grid(axis='y', alpha=0.3)
plt.show()

Key Benefits

  • Better focus ? Eliminates unnecessary whitespace above and below data
  • Improved readability ? Makes differences between bars more visible
  • Automatic scaling ? Adapts to your data range without manual adjustment

Conclusion

Use ylim() with max() and min() functions to automatically set Y-axis limits. Add small padding values to prevent bars from touching the axis boundaries for better visual appeal.

Updated on: 2026-03-25T21:27:03+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements