0

I want to fix the position of the ticks on the logarithmic scale, such that they are the same in each subplot (see red annotation in image). My code looks like this:

ax = fig.add_subplot(2,2, axis)
ax2 = ax.twinx()
ax2.set_yscale('log')
ax2.set_ylim(0,100)

Right now, set_yscale=('log') optimizes the tick spacing for each subplot. I prefer to adopt the tick spacing of the upper right subplot.

enter image description here

leermeester
  • 365
  • 3
  • 19

2 Answers2

1

You can achieve this by getting the limits of the left twin axis and setting it as the limits of the right twin axis.

Consider the following working example. Follow this procedure for the subplots you want to align the axes of.



import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 3))

axl = fig.add_subplot(121)
axr = fig.add_subplot(122)

ax1 = axl.twinx()
ax1.plot(np.logspace(-2, 3, 5))
ax1.set_yscale('log')

ax2 = axr.twinx()
ax2.plot(np.logspace(0, 3, 5))
ax2.set_yscale('log')

ax2.set_ylim(ax1.get_ylim()) # <-- This is the key line

plt.tight_layout()
plt.show()

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
0

OP's solution:

Plot a dummy curve and set alpha=0. Make sure the curve spans y_min and y_max.

fig = plt.figure()
axes = [1,2,3,4]

for axis in axes:
    ax = fig.add_subplot(2,2, axis)
    ax2 = ax.twinx()
    ax2.set_yscale('log')
    ax2.plot(x_dummy, y_dummy, alpha=0)            # <-- dummy plot

    x_real, y_real = func_that_loads_data()        # <-- your interesting plot 
    curve1 = ax2.plot(x_real, y_real)        

plt.show()

The solution provided by Sheldore was impractical to implement because I plot my data using a for-loop (unavoidable unless I escalate the number of variables).

Since I overwrite the ax variable on every iteration, I would have to save the y-limit as a global variable. Read here why global variables should be avoided.

ax = fig.add_subplot(2,2, axis)
ax2 = ax.twinx()
ax2.set_yscale('log') 

if axis == 1:
    global yscale
    yscale = ax2.get_ylim()                       # <-- where the magic happens
elif axis > 1:
    ax2.set_ylim(yscale)
leermeester
  • 365
  • 3
  • 19