我想用两个X轴绘制一些东西。但是,xticks不对齐。不知何故地忽略了边距?在最终版本中,xlabel是不同的,这意味着不能仅在顶部显示轴。
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10.0, 4.0))
axs = fig.subplots(2, 2)
xticklabels = [str(x) for x in range(0, 40+1, 5)]
y = np.random.rand(41*8)
ax0 = axs[0,0].twiny()
axs[0,0].set_xticks(np.arange(0,41*8,5*8))
axs[0,0].set_xticklabels(xticklabels)
ax0.set_xlim(axs[0,0].get_xlim())
ax0.set_xticks(np.arange(0,41*8,5*8))
ax0.set_xticklabels(xticklabels)
axs[0,0].plot(y)
plt.show()
编辑: 其实我想要这样的东西:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10.0, 4.0))
axs = fig.subplots(2, 2)
xticklabels = [str(x) for x in range(0, 40+1, 5)]
y = np.random.rand(41*8)
ax0 = axs[0,0].twiny()
axs[0,0].set_xticks(np.arange(0,41*8,5*8))
axs[0,0].set_xticklabels(xticklabels)
ax0.set_xlim(axs[0,0].get_xlim())
ax0.set_xticks(np.arange(10*8,31*8,5*8))
ax0.set_xticklabels(["0", "25", "50", "75", "100"])
axs[0,0].plot(y)
plt.show()
但是您可以看到刻度线不对齐。我快疯了!
答案 0 :(得分:1)
如果只想显示第二个x轴(不绘制任何东西),则使用scondary axis可能会更容易。您必须根据需要更改functions
:
import matplotlib.pyplot as plt
import numpy as np
y = np.random.rand(41*8)
fig,ax = plt.subplots()
ax.set_xticks(np.arange(0,41*8,5*8))
xticklabels = [str(x) for x in range(0, 41, 5)]
ax.set_xticklabels(xticklabels)
secx = ax.secondary_xaxis('top', functions=(lambda x: x/8, lambda x: x/8))
ax.plot(y)
plt.show()
我认为twiny
的问题是由于新轴上没有数据,但是
即使手动设置了数据间隔,我也无法使其正常工作。
根据评论和已编辑的问题进行更新:
secx = ax.secondary_xaxis('top', functions=(lambda x: 5*x/8-50, lambda x: 5*x/8-50))
secx.set_xticks([0,25,50,75,100])
secx.set_xticklabels([f'{x}' for x in secx.get_xticks()])
答案 1 :(得分:0)
好吧,我现在的解决方法是简单地用第二个轴绘制数据而没有颜色。
import matplotlib.pyplot as plt
import numpy as np
fig,axs = plt.subplots()
xticklabels = [str(x) for x in range(0, 40+1, 5)]
y = np.random.rand(41*8)
axs.set_xticks(np.arange(0,41*8,5*8))
axs.set_xticklabels(xticklabels)
ax0 = axs.twiny()
ax0.set_xticks(np.arange(10*8,31*8,5*8))
ax0.set_xticklabels(["0", "25", "50", "75", "100"])
axs.plot(y)
ax0.plot(y, color ="None")
plt.show()