更改X的刻度频率(时间频率,而非数量)

32
我的Python绘图数据只在x轴上显示了2个点。
我想要更多,但不知道如何做。
x = [ datetime.datetime(1900,1,1,0,1,2),
      datetime.datetime(1900,1,1,0,1,3),
      ...
      ]                                            # ( more than 1000 elements )
y = [ 34, 33, 23, ............ ]

plt.plot( x, y )

X轴只显示了2个间隔点。我尝试使用.xticks,但对X轴没有起作用。 它产生了以下错误:

TypeError: object of type 'datetime.datetime' has no len()

你使用的 mpl 版本是什么? - tacaswell
我真的不明白你的问题。 - tacaswell
你确定只有两个点被显示了吗?你可以通过以下方式查看绘图器认为它拥有的数据: plt.gca().lines[0].get_data() 这些点可能只是太靠近了,导致看起来像只有两个点。 - Lukeclh
1个回答

54
无论出于何种原因,如果您只能默认获得2个勾号,则可以通过使用日期定位器更改股票定位器来修复(自定义)它。
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

x = [ datetime.datetime(1900,1,1,0,1,2),
      datetime.datetime(1900,1,1,0,1,3),
      ...
      ]                                            # ( more than 1000 elements )
y = [ 34, 33, 23, ............ ]

fig = plt.figure()
ax = fig.add_subplot(1,1,1)  
plt.plot( x, y )

ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=15))   #to get a tick every 15 minutes
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))     #optional formatting 

您有几个定位器(例如:DayLocator、WeekdayLocator、MonthLocator等),请在文档中阅读相关内容:

http://matplotlib.org/api/dates_api.html

但也许这个示例会更有帮助:

http://matplotlib.org/examples/api/date_demo.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接