Python Forum

Full Version: How matplotlib automatically set x-axis and y-axis limits for bar graph ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am confused in math/logic behind automatically by-default setting of x-axis and y-axis limits in bar graph ? Here i am sharing some examples

1.
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [1000, 1002, 1001, 1003, 1005]
plt.bar(x,y) 
plt.show()
In this bar graph, X axis limits are 0,1,2,3,4,5 and Y axis limits are 0,200,400,600,800,1000. How is happened??

2.
import matplotlib.pyplot as plt
x=[20,30,90,70, 50, 60, 80, 70]
y=[3,2,5,10, 3, 9, 7, 6]
plt.bar(x,y)
plt.show()
In this bar graph, X axis limits are 0,20,30,40,50,60,70,80,90 and Y axis limits are 0,2,4,6,8,10. How is happened??
If you look at plt.bar function docs, you find keyword bottom; its default value 0, that means all bars will start at 0 and have
height as defined in the second argument passed to bar (y).

By default, matplotlib chooses axes limits to cover provided range of values. Note, bar function plots filled rectangles of specified heights, so, by default matplotlib chooses axes to cover range from 0 (bottom value) to (bottom + y). Ticks and tick labels are placed in regular manner.

Check out axes.set_xticks, axes.set_xticklabels, axes.set_xlim (you can get current axes instance using plt.gca()) to change this behavior.
(Jul-03-2019, 11:37 AM)scidam Wrote: [ -> ]If you look at plt.bar function docs, you find keyword bottom; its default value 0, that means all bars will start at 0 and have
height as defined in the second argument passed to bar (y).

By default, matplotlib chooses axes limits to cover provided range of values. Note, bar function plots filled rectangles of specified heights, so, by default matplotlib chooses axes to cover range from 0 (bottom value) to (bottom + y). Ticks and tick labels are placed in regular manner.

Check out axes.set_xticks, axes.set_xticklabels, axes.set_xlim (you can get current axes instance using plt.gca()) to change this behavior.

please explain first example where Y axis limits are 0,200,400,600,800,1000. How these limit/range comes in graph ?
I didn't explore source code of matplotlib in detail, but in general, computation of values where ytick labels will be shown is performed by a matplotlib.ticker instance. By default, it is ticker.AutoLocator:

from matplotlib.ticker import AutoLocator
aul = AutoLocator()
aul.tick_values(1, 3)
Output:
array([1. , 1.25, 1.5 , 1.75, 2. , 2.25, 2.5 , 2.75, 3. ])
from pylab import *
plt.plot([1,2,3])
plt.show() # yields a graph with ticks placed in above positions
This default behavior is made for convenience, and it could be easily overridden using axes.set_yticks etc. Note, there are minor and major ticks (we are talking about major one here), so underlying machinery is quite tricky.