Reputation: 669
I'm trying to draw nice ticks (scalar not exponential) on a logarithmic y-axis in matplotlib. In general I want to include the first value (100
in this example) an work from there. But in some cases I get different tickers like below. I have found no clue as how to manage this. Is there an uncomplicated way to force matplotlib to start with a specific value and automatically select sensible tickers thereafter (in this example 120, 110, 100, 90, 80, 70, 60, 50, 40, 30, 20
would be nice).
My code:
from matplotlib.ticker import ScalarFormatter, MaxNLocator
x = range(11)
y = [ 100., 91.3700879 , 91.01104689, 58.91189746,
46.99501432, 55.3816625 , 37.49715841, 26.55818469,
36.34538328, 37.7811044 , 47.45953131]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_yscale('log')
ax.yaxis.set_major_locator(MaxNLocator(nbins=11, steps=[1,2,3,4,5,6,7,8,9,10]))
ax.yaxis.set_major_formatter(ScalarFormatter())
ax.plot(x,y)
Result:
Upvotes: 1
Views: 335
Reputation: 85422
You can use set_ylim()
:
ax.set_ylim(20, 120)
This could be one way to make the limits depend on the y-data instead of hard-wiring them:
ymax = round(max(y), -1) + 10
ymin = max(round(min(y), -1) - 10, 0)
ax.set_ylim(ymin, ymax)
You can force the tick locations with ax.set_yticks()
:
ymax = round(max(y), -1) + 20
ymin = max(round(min(y), -1) - 10, 0)
ax.set_ylim(ymin, ymax)
ax.set_yticks(range(int(ymin), int(ymax) + 1, 10))
ax.plot(x,y)
For:
y = [ 100. , 114.088362 , 91.14833261, 109.33399855, 73.34902925,
76.43091996, 56.84863363, 65.34297117, 78.99411287, 70.93280065,
55.03979689]
it produces this plot:
Upvotes: 1