如何解决如何移动第二个x轴的位置?
我正在尝试创建带有辅助x轴的图形,但是我希望标签和辅助x轴的刻度线位于第一个下方。我目前仅找到将其移至底部而不是精确位置的方法。我已附上我要实现的目标的图像。
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()
解决方法
答案
首先,您必须包括所需的库:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
然后您可以使用生成第一个轴
ax = host_subplot(111,axes_class = AA.Axes,figure = fig)
然后通过以下方式生成辅助轴
ax2=ax.twiny()
这时您需要为辅助轴留一些空间,因此您应该使用以下方法来增加绘图区域的底部
plt.subplots_adjust(bottom = 0.2)
最后将辅助轴定位在第一个轴的下方
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,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',offset))
ax2.axis['bottom'].toggle(all = True)
ax2.plot(x[1],y)
ax2.set_xlabel("Velocity km/hr")
plt.show()
结果
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。