Sanoj
Sanoj

Reputation: 300

set equal amount of y-ticks for every subplot

I am trying to plot a nice subplot graph, but I am unable to fix the problem of an unequal number of y-ticks. In the image below, for example the "VVIX Beta" plot has only 3 ticks, while others have four to five. Ideally I would like to have five y-ticks for each graph. Similar questions have already been asked, and suggested:

ax1.locator_params(axis='y', nbins=5)

where ax1 to ax7 are the seven subplots. This however didn't work, the output seemed to ignore the command. Does anyone know an alternative approach? Any help is highly appreciated and thanks in advance

enter image description here

Upvotes: 0

Views: 291

Answers (1)

Valdi_Bo
Valdi_Bo

Reputation: 30971

One of possible options is to use MaxNLocator, passing:

  • nbins as the number of ticks,
  • min_n_ticks smaller by one from nbins.

Look at the following example:

import matplotlib.ticker as ticker

def draw(ax, nBins):
    ax.plot(x,  y, 'g', label='line one', linewidth=3)
    ax.plot(x2, y2,'c', label='line two', linewidth=3)
    ax.set_title('Epic Info')
    ax.set_ylabel('Y axis')
    ax.set_xlabel('X axis')
    if nBins > 0:
        ax.yaxis.set_major_locator(ticker.MaxNLocator(nbins=nBins, min_n_ticks=nBins-1))
    else:
        ax.yaxis.set_major_locator(ticker.MaxNLocator(nbins='auto'))
    ax.legend()
    ax.grid(True, color='k')

x =  [ 5, 8,10]; y =  [12.1,15.2, 6.3]
x2 = [ 6, 9,11]; y2 = [ 5.4,15.5, 7.6]
fig, axs = plt.subplots(2, 2, figsize=(10,7), constrained_layout=True)
fig.suptitle('Global title')
draw(axs.flat[0], 4)
draw(axs.flat[1], 5)
draw(axs.flat[2], 6)
draw(axs.flat[3], 0)
plt.show()

As you can see, it generates 4 almost identical plots:

  • 3 with explicitely defined number of y ticks,
  • and the last with auto setting.

The result is:

enter image description here

Caution: For some nBins the actual number of ticks is different than expected, but at least you can experiment with my code to draw your data.

Upvotes: 1

Related Questions