matplotlib - How can I use MaxNLocator and specify a number which has to be in an axis?

10,537

Assuming that you know in advance how many plots there will be in 1 row on a page one way to solve this would be to put all those plots into one figure - matplotlib will make sure they are alinged on axes:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

x = np.linspace(0, 1, num=11)
y = np.linspace(1, .42, num=11)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,3), gridspec_kw={'wspace':.2})
ax1.plot(x,y)
ax2.plot(x,y)

locator=MaxNLocator(prune='both', nbins=5)
ax1.yaxis.set_major_locator(locator)

# You don't need to use tight_layout and using it might give an error
# plt.tight_layout()  

fig.show()

enter image description here

Share:
10,537
Laenan
Author by

Laenan

Chemist at a University, I do much coding for data analysis and plotting.

Updated on June 05, 2022

Comments

  • Laenan
    Laenan almost 2 years

    I do have a question with matplotlib in python. I create different figures, where every figure should have the same height to print them in a publication/poster next to each other.

    If the y-axis has a label on the very top, this shrinks the height of the box with the plot. So I use MaxNLocator to remove the upper and lower y-tick. In some plots, I want to have the 1.0 as a number on the y-axis, because I have normalized data. So I need a solution, which expands in these cases the y-axis and ensures 1.0 is a y-Tick, but does not corrupt the size of the figure using tight_layout().

    Here is a minimal example:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import MaxNLocator
    
    x = np.linspace(0,1,num=11)
    y = np.linspace(1,.42,num=11)
    
    fig,axs = plt.subplots(1,1)
    axs.plot(x,y)
    
    locator=MaxNLocator(prune='both',nbins=5)
    axs.yaxis.set_major_locator(locator)
    
    plt.tight_layout()
    
    fig.show()
    

    Here is a link to a example-pdf, which shows the problems with height of upper boxline.

    I tried to work with adjust_subplots() but this is of no use for me, because I vary the size of the figures and want to have same the font size all the time, which changes the margins.

    Question is:

    How can I use MaxNLocator and specify a number which has to be in the y-axis?

    Hopefully someone of you has some advice.

    Greetings, Laenan

  • Laenan
    Laenan over 8 years
    This would solve the problem in general. I would like to include the figures in TeX separately with different captions, so this is not a solution for me.
  • Laenan
    Laenan about 8 years
    Because it solves the question in general, answer accepted.