Issue is with semilogy
, not with twinx
. From next code
import numpy as np
import matplotlib.pyplot as plt
def plot_me(x):
fig, ax1 = plt.subplots()
ax1.semilogy(x, color="blue")
for label in ax1.get_yticklabels():
label.set_color("blue")
ax2 = ax1.twinx()
ax2.semilogy(1/x, 'red')
for label in ax2.get_yticklabels():
label.set_color("red")
plot_me(np.arange(.1, 1.3, 1e-1))
goes through 1e-1 and 1e0 in left y-axis, through another two logs in right on. All ok:
on the other hand plot_me(np.arange(.1, .3, 1e-2))
does not pass at least two log10 (in neither left nor right y-axis), thus both axis got aside 1 log10 y-tick also non log10 y-ticks, which I cannot proper color:
Furthermore, the y-ticks from a semilog
are all log10, which contradict what we have seen in y-ticks labels of previous plots!
def print_y_ticks(x):
fig, ax1 = plt.subplots()
ax1.semilogy(x, color="blue")
for label in ax1.get_yticklabels():
label.set_color("blue")
print(ax1.get_yticks())
return ax1
ax = print_y_ticks(np.arange(.1, 1.3, 1e-1)) # [1.e-03 1.e-02 1.e-01 1.e+00 1.e+01 1.e+02]
ax = print_y_ticks(np.arange(.1, .3, 1e-2)) # [1.e-03 1.e-02 1.e-01 1.e+00 1.e+01]
My workaround is next:
import numpy as np
import matplotlib.pyplot as plt
def ticks2log(ax):
yticks = ax.get_yticks()
ax.set_yticks(yticks, [f'{k:.1e}' for k in yticks])
return ax
def plot_me_new(x1, x2):
x1 = np.log10(x1)
x2 = np.log10(x2)
fig, ax1 = plt.subplots()
ax1.plot(x1, lw=2, color="blue")
ax1 = ticks2log(ax1)
for label in ax1.get_yticklabels():
label.set_color("blue")
ax2 = ax1.twinx()
ax2.plot(x2, lw=2, color="red")
ax2 = ticks2log(ax2)
for label in ax2.get_yticklabels():
label.set_color("red")
Result of x = np.arange(.1, .3, 1e-2); plot_me_new(x, 1/x)
is proper colored, but much more tedious.
Thanks in advance for the help!
PD: issue is with semilogy
, not with twinx
.
ax.get_yticklabels(which='both')
Solved by JohanC