matplotlib: How to add linear secondary_yaxis for log-scale primary axis?

Viewed 278

I am having a plot with two y-axes, where the second one is some function of the values of the first one. For this I am using the secondary_yaxis function. I want to make this work for the case that the primary axis is logarithmic.

This works very well if the first axis is linear, e.g.:

import matplotlib.pyplot as plt
import numpy as np

def inverse(x):
    return -7 * np.log(x / 1013.25)

def forward(x):
    return 1013.25 * np.exp(-x / 7)

data = np.array([0.1, 0.4, 0.3, 0.3, 0.8, 0.9])
alt = np.array([0, 5, 8, 15, 17, 20])

fig, ax = plt.subplots(nrows=1)
ax.plot(data, alt)
ax.set_ylim([0, 20])
ax1 = ax.secondary_yaxis("right", functions=(forward, inverse))

This creates this plot with a correct secondary axis
enter image description here

Now I try to do the same, but the other way round, i.e. the logarithmic (pressure) axis is the primary axis:

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

def forward(x):
    return -7 * np.log(x / 1013.25)

def inverse(x):
    return 1013.25 * np.exp(-x / 7)

data = np.array([0.1, 0.4, 0.3, 0.3, 0.8, 0.9])
pres = np.array([1000, 800, 600, 500, 300, 100])

fig, ax = plt.subplots(nrows=1)

ax.plot(data, pres)
ax.set_yscale("log")
ax.get_yaxis().set_major_formatter(ScalarFormatter())
ax.get_yaxis().set_minor_formatter(ScalarFormatter())
ax.set_ylim([1000, 100])

ax1 = ax.secondary_yaxis("right", functions=(forward, inverse))

The values on the secondary axis seem to be correct, but the ticks are logarithmic, as inherited from the primary axis: enter image description here

Now I can add ax1.set_yscale("linear"), but the the values are also transformed, resulting in the wrong values on correct linear ticks:

enter image description here

I am not finding a way to fix this. Any ideas?

(In the real-world script, I am using an interpolation function for the inverse/forward functions here).

0 Answers
Related