Search code examples
python-3.xmatplotlibaxis-labelsmultiple-axes

y-axis ticks doesn't look nice powers of 10 when the axis has logarithmic scale in a plot with double y axes


I'm trying to make a plot with two y-axes, both of them logarithmic; Y1 is the left-hand y-axis and Y2 is the right-hand y-axis. Here the values of Y1 are calculated by dividing Y2 values by some_number to be defined in the snippet. The figure does not look ok due to decimal numbers picked for Y2 axis:

import numpy as np
from numpy import *
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import rcParams, cm
from matplotlib.ticker import MaxNLocator

#Plotting Decorations
xtick_label_size, ytick_label_size, axes_label_size, font_size, tick_width, lw, alpha = 18, 18, 20, 30, 2, 0.5, 0.5
plt.rcParams['mathtext.fontset'] = 'stix'
plt.rcParams['font.family'] = 'STIXGeneral'
mpl.rcParams['xtick.labelsize'], mpl.rcParams['ytick.labelsize'], mpl.rcParams['axes.labelsize'] = xtick_label_size, ytick_label_size, axes_label_size

some_number = mean(array([0.01614, 0.01381, 0.02411, 0.007436, 0.03223]))
f, (ax) = plt.subplots(1, 1, figsize=(10,100))

ax.set_xlim([1e8, 3e12])
ax.set_ylim([3e-1, 3e3])
ax.yaxis.set_major_locator(MaxNLocator(prune='upper')) 
ax.set_ylabel('Y1', fontsize=12)
ax.set_xlabel('X', fontsize=12)
ax.set_xscale("log", nonposx='clip')
ax.set_yscale("log", nonposy='clip')
ax.xaxis.set_tick_params(width=tick_width)
ax.yaxis.set_tick_params(width=tick_width)
ax.get_xaxis().tick_bottom()  
ax.get_yaxis().tick_left()
number = np.array([1e-4,1e-3,1e-2,1e-1,1,1e1,1e2,1e3])
numberticks = [i*some_number for i in number]
axsecond = ax.twinx()
axsecond.set_ylabel('Y2', fontsize=12)
axsecond.set_yscale("log", nonposy='clip')
axsecond.yaxis.set_tick_params(width=tick_width)
axsecond.set_yticks(number)
axsecond.set_yticklabels(['{:g}'.format(i) for i in numberticks])

f.subplots_adjust(top=0.98,bottom=0.14,left=0.14,right=0.98)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=True)
f.tight_layout()
plt.show()

After getting help for defining correct labels for Y2, I want to represent these labels as powers of 10 similar to Y1. Do you know how to do that?

enter image description here


Solution

  • The idea would be to synchronize the axes limits. I.e. if the y limits of the first axes are [a,b], those for the second axes would need to be [a*factor, b*factor].

    import matplotlib.pyplot as plt
    import numpy as np
    
    factor = 0.5
    
    fig, ax = plt.subplots()
    ax2 = ax.twinx()
    
    ax.set_ylim([.1, 1e3])
    ax2.set_ylim(np.array(ax.get_ylim())*factor)
    
    ax.set_yscale("log")
    ax2.set_yscale("log")
    
    
    ax.plot([0,1],[1,100])
    ax2.plot([0,1],np.array([1,100])*factor)
    
    plt.show()
    

    enter image description here