I am trying to do a plot with a second x-axis on matplotlib but with a logarithmic scale.
I managed to add a second x-axis on a plot with a linear scale using the example below:
import numpy as np
import matplotlib.pyplot as plt
x_axis = np.linspace(0,100, 100)
yvalues = x_axis**3
new_tick_locations = np.array([20,40,60,80,100])
second_x_axis = new_tick_locations**2
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x_axis, yvalues)
ax1.axvline(x = 60, color = 'black', linestyle = 'dotted')
ax1.set_xlabel("first x axis")
ax1.set_ylabel("yvalues")
SecondAxis = True
if(SecondAxis):
ax2 = ax1.twiny()
ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks(new_tick_locations )
ax2.set_xticklabels(second_x_axis)
ax2.set_xlabel("second x axis")
Logscale = False
if(Logscale):
ax1.set_xscale("log")
ax1.set_yscale("log")
plt.show()
Here, my second x-axis is defined as the square of my x-axis and we retrieve on the plot that for x =60 we have second_x =3600.
However, if I now set the "Logscale" variable in my code to "True" I get the following result:
Where the values of my second x-axis do not match the ones of my first x-axis.
Does anyone know how to fix this problem?