如何调整Matplotlib绘图中x轴次刻度(minor ticks)的数量
matplotlib x轴次刻度数量调整方案
你当前代码生成的x轴相邻主刻度间隔为20*time_step,次刻度间隔设置为2*time_step,因此两个主刻度之间的次刻度数量为 (20 / 2) - 1 = 9,和你反馈的现象一致。
要将两个主刻度之间的次刻度数量调整为4个,仅需要修改次刻度定位器的间隔参数即可:
- 找到
plotSignal函数中的次刻度定位器代码行 - 将原来的
ax0.xaxis.set_minor_locator(ticker.MultipleLocator(2*time_step)) - 修改为
ax0.xaxis.set_minor_locator(ticker.MultipleLocator(4*time_step))
修改原理:4个次刻度会将两个主刻度的间隔平分为5等份,因此次刻度间隔应为20*time_step / 5 =4*time_step,代入后两个主刻度之间的次刻度数量为(20 /4 ) -1 =4,完全符合要求。
修改后的完整plotSignal函数参考:
def plotSignal(theTimeVec,theData,theLabel): fig,ax0 = plt.subplots(1,1, facecolor='0.75', linewidth=3, edgecolor='Black') ax0.plot(theTimeVec,theData,label=theLabel) ax0.legend(loc='center left',framealpha=0.3,facecolor='Green') if theLabel == 'none': ax0.legend_.remove() ax0.set_xlabel('Time in seconds') ax0.grid(True) freq_interval = (theTimeVec[1]) ax0.xaxis.set_major_locator(ticker.MultipleLocator(20*time_step)) # 仅修改了下面这一行的间隔参数 ax0.xaxis.set_minor_locator(ticker.MultipleLocator(4*time_step)) ax0.tick_params(axis='both',which='minor',length=5) ax0.tick_params(axis='both',which='major',color='black', length=10,labelcolor='blue',width=2) ax0.xaxis.set_major_formatter(FormatStrFormatter('%.3f'))
内容的提问来源于stack exchange,提问作者homerwight
相关产品推荐
相关产品推荐

