Matplotlib刻度对齐
我想在我的图表的顶部和底部都有两个刻度线。可惜的是,这些刻度线在这个图上对不上齐:
http://puu.sh/cE2Ez/f270ab625e.png
根据我的代码:
plt.xlim([0, ncols])
plt.ylim([0, nrows])
plt.gca().invert_yaxis()
plt.tick_params(axis='both', which='both', left='off', right='off', top='off', bottom='off')
plt.tight_layout()
#ticks
rect.set_yticks([0, 64, 128, 192, 256])
rect.get_yaxis().set_major_formatter(ticker.ScalarFormatter())
rect.tick_params(axis='both', which='both', left='off', right='off', top='off', bottom='off', labelsize=6)
xaxisbot = [int(args.UTC_time) + 11 * 110 * x for x in range(1833 / 110 + 1)]
xaxistop = [x2 * 110 for x2 in range(1833/110+1)]
plt.xticks(xaxistop, xaxisbot)
rect2 = rect.twiny()
rect2.tick_params(axis='both', which='both', left='off', right='off', top='off', bottom='off', labelsize=6)
rect2.set_xticks(xaxistop)
rect2.xaxis.tick_top()
这些刻度线似乎没有对齐。我有没有更好的方法来让它们对齐,特别是当我使用标签的时候?
另外,当我尝试在一个循环中创建很多这样的图表时,这些刻度线会重叠在一起,而不是删除和清空。不过,当我使用cla()时,我的图表都不生成。有没有办法解决这个问题?
1 个回答
1
你的代码看起来很复杂,建议你去掉那些和问题无关的部分,提供一个最小可工作示例。特别是,我们无法运行你的代码,因为rect
和args
没有定义!
根据我了解到的情况,问题出现在这段代码之后,你在rect
或rect2
上绘制数据。我猜这两个是坐标轴的实例。如果是这样的话,下面的代码可以重现这个问题:
import matplotlib.pyplot as plt
import numpy as np
ax1 = plt.subplot(111)
xaxisbot = [11 * 110 * x for x in range(1833 / 110 + 1)]
xaxistop = [x2 * 110 for x2 in range(1833/110+1)]
ax1.tick_params(labelsize=6)
ax1.set_xticks(xaxisbot)
ax2 = ax1.twiny()
ax2.tick_params(labelsize=6)
ax2.set_xticks(xaxistop)
ax2.xaxis.tick_top()
# Add data to ax2
ax2.plot(range(1500), range(1500))
ax.grid()
plt.show()
所以要解决这个问题,你只需要手动设置坐标的范围。例如,可以添加:
ax1.set_xlim(xaxisbot[0], xaxisbot[-1])
ax2.set_xlim(xaxistop[0], xaxistop[-1])
或者,按照你提供的代码来说:
rect.set_xlim(xaxisbot[0], xaxisbot[-1])
rect2.set_xlim(xaxistop[0], xaxistop[-1])
另外,你应该看看你代码中的这一行plt.xticks(xaxistop, xaxisbot)
,这真的是你想要的吗?我觉得这不太合理,但它似乎有其目的……