Search code examples
pythonmatplotlibxticks

Set xticks relative to the plot coordinates


Is there a simple way to set two xticks at even distances from the xmin and xmax, for two plots with different ranges on the x-axis?

# Example: 
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(6,4), constrained_layout=True)
gs = gridspec.GridSpec(ncols=2, nrows=1, figure=fig)

x1 = [1,   0.6,  0.4,  0.3,  0.25,   0.24,   0.23]
x2 = [0.1, 0.14, 0.15, 0.16, 0.166,  0.1666, 0.1666 ]
y  = [1, 2, 3, 4, 5, 6, 7]

# xticks 
number_of_xticks = 2

# Plot 1:
ax0 = fig.add_subplot(gs[0, 0]) 
ax0.plot(x1, y)
ax0.xaxis.set_major_locator(plt.MaxNLocator(number_of_xticks))

# Plot 2:
ax1 = fig.add_subplot(gs[0, 1]) 
ax1.plot(x2, y)
ax1.xaxis.set_major_locator(plt.MaxNLocator(number_of_xticks))

plt.show()

Example code does not work because xticks are at different distances from the xmin and xmax in the two plots:


Solution

  • You could try specifying the relative distance along the x-range:

    # xticks 
    tick_fractions = [1/4, 3/4]
    

    And then calculate the tick positions based on each x-range:

    mini = min(x)
    maxi = max(x)
    dist = maxi - mini
    ax.set_xticks([mini + f * dist for f in tick_fractions])
    

    So full script would look like:

    # Example: 
    from matplotlib import pyplot as plt
    import matplotlib.gridspec as gridspec
    
    fig = plt.figure(figsize=(6,4), constrained_layout=True)
    gs = gridspec.GridSpec(ncols=2, nrows=1, figure=fig)
    
    x1 = [1,   0.6,  0.4,  0.3,  0.25,   0.24,   0.23]
    x2 = [0.1, 0.14, 0.15, 0.16, 0.166,  0.1666, 0.1666 ]
    y  = [1, 2, 3, 4, 5, 6, 7]
    
    # xticks 
    tick_fractions = [1/4, 3/4]
    
    # Plot 1:
    ax0 = fig.add_subplot(gs[0, 0]) 
    ax0.plot(x1, y)
    mini = min(x1)
    maxi = max(x1)
    dist = maxi - mini
    ax0.set_xticks([mini + f * dist for f in tick_fractions])
    
    # Plot 2:
    ax1 = fig.add_subplot(gs[0, 1]) 
    ax1.plot(x2, y)
    mini = min(x2)
    maxi = max(x2)
    dist = maxi - mini
    ax1.set_xticks([mini + f * dist for f in tick_fractions])
    
    plt.show()
    

    enter image description here

    You could add a call to round somewhere if you want to limit the decimals.