Reputation: 347
I am trying to create a graph with a secondary x-axis however I want the label and the ticks of the secondary x-axis to lie under the first. I have currently only found methods to move it to the bottom and not to an exact position. I have attached an image of what I am trying to achieve.
y = [3, 5, 2, 8, 7]
x = [[10, 11, 12, 13, 14], [36, 39.6, 43.2, 46.8, 50.4]]
labels = ['m/s', 'km/hr']
fig,ax = plt.subplots()
ax.plot(x[0], y)
ax.set_xlabel("Velocity m/s")
ax.set_ylabel("Time /mins")
ax2=ax.twiny()
ax2.plot(x[1], y)
ax2.set_xlabel("Velocity km/hr")
plt.show()
Upvotes: 1
Views: 1096
Reputation: 12496
Firstly you have to include the required libraries:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
then you could generate the first axis with
ax = host_subplot(111, axes_class = AA.Axes, figure = fig)
then generate the secondary axis by
ax2=ax.twiny()
At this point you need to make some space for the secondary axis, therefore you should raise the bottom of the plot area with
plt.subplots_adjust(bottom = 0.2)
and finally position the secondary axis under the first one by
offset = -40
new_fixed_axis = ax2.get_grid_helper().new_fixed_axis
ax2.axis['bottom'] = new_fixed_axis(loc = 'bottom',
axes = ax2,
offset = (0, offset))
ax2.axis['bottom'].toggle(all = True)
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
y = [3, 5, 2, 8, 7]
x = [[10, 11, 12, 13, 14], [36, 39.6, 43.2, 46.8, 50.4]]
labels = ['m/s', 'km/hr']
fig = plt.figure()
# generate the first axis
ax = host_subplot(111, axes_class = AA.Axes, figure = fig)
ax.plot(x[0], y)
ax.set_xlabel("Velocity m/s")
ax.set_ylabel("Time /mins")
ax2=ax.twiny()
# make space for the secondary axis
plt.subplots_adjust(bottom = 0.2)
# set position ax2 axis
offset = -40
new_fixed_axis = ax2.get_grid_helper().new_fixed_axis
ax2.axis['bottom'] = new_fixed_axis(loc = 'bottom',
axes = ax2,
offset = (0, offset))
ax2.axis['bottom'].toggle(all = True)
ax2.plot(x[1], y)
ax2.set_xlabel("Velocity km/hr")
plt.show()
Upvotes: 1