matplotlib刻度线与数据点不对齐 [英] matplotlib ticks not align with data point
问题描述
我已经修改了示例,但似乎是 x 刻度线位置如果设置nbins = 10不正确!但如果设置 nbins=5,它工作正常.我怎么了?
I have modified the example but it seems the x tick mark position not correct if set nbins=10! but it works fine if set nbins=5. what's wrong with me?
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from time import mktime
from datetime import datetime
from matplotlib.ticker import MaxNLocator
#%matplotlib inline
#-----------------------------------------#
def main():
ticks = [ "9-28 11:07:57.435", "9-28 11:10:00.123", "9-28 11:40:00.654", "9-28 11:50:00.341", "9-28 12:00:00.773"]
y = np.array([10, 12, 9, 15, 11])
x = [mktime(datetime.strptime("2014-"+i, "%Y-%m-%d %H:%M:%S.%f").timetuple()) for i in ticks]
plt.stem(x,y)
plt.xticks(x, ticks,rotation=25,ha='right')
plt.gca().xaxis.set_major_locator(MaxNLocator(nbins=10, prune = 'lower'))
plt.gca().spines['right'].set_color('none')
plt.gca().spines['top'].set_color('none')
plt.gca().spines['left'].set_smart_bounds(True)
plt.gca().spines['bottom'].set_smart_bounds(True)
plt.gca().xaxis.set_ticks_position('bottom')
plt.gca().yaxis.set_ticks_position('left')
plt.show()
return
#-----------------------------------------#
if __name__ == "__main__":
main()
推荐答案
当您指定 plt.xticks
时,它所做的是将刻度定位器设置为 FixedLocator,允许您明确放置刻度.当您将刻度定位器分配给 MaxNLocator 时,您将覆盖显式刻度位置.
When you specify plt.xticks
, what it does is set the tick locator to a FixedLocator, allowing you to place the ticks explicitly. When you then assign the tick locator to a MaxNLocator, you override the explicit tick placement.
要获得最多 N 个刻度,您可以从刻度列表中提取 N 个值并将它们传递给 xticks,无需手动设置定位器.例如,这些行从您当前的 5 个列表中提取了 3 个刻度.
To get a maximum of N ticks, you can pull N values from your ticks list and just pass those to xticks, and eliminate setting the locator manually. These lines pull 3 ticks out of your current list of 5 as an example.
inds = np.linspace(0,len(ticks)-1,3).astype(int)
plt.xticks(np.array(x)[inds], np.array(ticks)[inds],rotation=25,ha='right')
这篇关于matplotlib刻度线与数据点不对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!