Python 在 matplotlib 中更改 X(时间,而不是数字)频率上的滴答频率

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25538520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:21:32  来源:igfitidea点击:

Change tick frequency on X (time, not number) frequency in matplotlib

pythonmatplotlib

提问by Kensg

My pythonplot data only show 2 points on x axis.

我的python绘图数据仅在 x 轴上显示 2 个点。

I would like to have more, but don't know how.

我想要更多,但不知道如何。

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 )

The X axis only shows 2 points of interval. I tried to use .xticksbut didn't work for X axis. It gave the below error:

X 轴仅显示 2 个间隔点。我尝试使用.xticks但不适用于 X 轴。它给出了以下错误:

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

回答by Sebastian

Whatever reason it is you are getting 2 ticks only by default, you can fix it (customise it) by changing the ticker locator using a date locator.

无论是什么原因,默认情况下您只能获得 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 

You have several locators (for example: DayLocator, WeekdayLocator, MonthLocator, etc.) read about it in the documentation:

您在文档中阅读了多个定位器(例如:DayLocator、WeekdayLocator、MonthLocator 等):

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

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

But maybe this example will help more:

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

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

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