简体   繁体   中英

How to set the ticks on a logarithmic axis in matplotlib

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:

在此处输入图片说明

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM