1

I want to create a plot with two x axis and also two y axis. I am using twiny and twinx to do it. The secondary axis are just a rescaling of the original ones, so I'm applying a transformations to get the ticks. The problem is that I am in log scale, so the separation between the ticks does not match between the original and the twin ax. Moreover, the second x axis has other values that I don't want. Let's follow an example to explain better:

#define the transformations I need
h=0.67
def trasf_log(y):
    y_ = 10**y
    return y_/h

def trasf_sigma(x):
    return 1.68/x

#plot in log scale and with ticks that I choose
fig,ax = plt.subplots(1)
ax.plot(x,y0)
ax.set_ylim(1.0,2.4)
ax.set_xlim(0.6,5)
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xticks([0.6,0.8,1,2,3,4])
ax.set_yticks([1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4])
ax.xaxis.set_major_formatter(ScalarFormatter())
ax.yaxis.set_major_formatter(ScalarFormatter())
ax.ticklabel_format(axis='both', style='plain')
ax.set_xlabel(r'$\nu$', fontsize=20)
ax.set_ylabel(r'$\log_{10}Q$', fontsize=20)
ax.tick_params(labelsize=15)

#create twin axes
ax1 = ax.twinx()
ax1.set_yscale('log')
ymin,ymax=ax.get_ylim()
ax1.set_ylim((trasf_log(ymin),trasf_log(ymax)))
ax1.set_yticks(trasf_log(ax.get_yticks()))
ax1.yaxis.set_major_formatter(ScalarFormatter())
ax1.ticklabel_format(axis='y', style='plain')
ax1.tick_params(labelsize=15,labelleft=False,labelbottom=False,labeltop=False)
ax1.set_ylabel(r'$Q$', fontsize=20)

ax2 = ax.twiny()
ax2.set_xscale('log')
xmin,xmax=ax.get_xlim()
ax2.set_xlim((trasf_sigma(xmin),trasf_sigma(xmax)))
ax2.set_xticks(trasf_sigma(ax.get_xticks()))
ax2.xaxis.set_major_formatter(ScalarFormatter())
ax2.ticklabel_format(axis='x', style='plain') 
ax2.tick_params(labelsize=15,labelleft=False,labelbottom=False,labelright=False)
ax2.set_xlabel(r'$\sigma $', fontsize=20)

ax.grid(True)
fig.tight_layout()
plt.show()

This is what I get:

enter image description here

The values of the new x and y axis are not aligned with the original ones. For example, on the two x axis the values 1 and 1.68 should be aligned. Same thing for the y axis: 1.2 and 23.7 should be aligned. Moreover, I don't understand where the other numbers on the second x axis are coming from. I tried already applying Scalar Formatter to each axis with 'plain' style, but nothing changes. I also tried using secondary_axis, but I could not find a solution as well.

Anyone knows a solution?

imbr
  • 6,226
  • 4
  • 53
  • 65
rseppi
  • 21
  • 3

0 Answers0