将日期代码添加到matplotlib/python图表

Mat*_*NNZ 6 python matplotlib

我有一个听起来很简单的问题,但它让我疯了几天.我有一个历史时间序列在两个列表中关闭:第一个列表包含价格,让我们说P = [1,1.5,1.3 ...],而第二个列表包含相关日期,让我们说D = [01/01/2010,02/01/2010 ...].我想做的是绘制这些日期中的一些(当我说"某些"是因为我到目前为止所获得的"最佳"结果是将所有这些显示为代码,因此在其中创建了一个黑色的不可读数据云. x轴)当放大时,会更详细地显示.这张照片现在具有Matplotlib制作的渐进式自动化范围:

缩小

而不是0,200,400等.我想要绘制与数据点相关的日期值.而且,当我放大时,我得到以下内容:

放大

除了我得到0到200之间的细节(20,40等)我想把日期附在列表上.我确定这是一个简单的问题要解决,但我是Matplotlib以及Python的新手,任何提示都会受到赞赏.提前致谢

Tho*_*anz 11

Matplotlib为绘制日期提供了复杂的支持.我建议使用AutoDateFormatter和AutoDateLocator.它们甚至是特定于语言环境的,因此它们根据您的语言环境选择月份名称.

import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateFormatter, AutoDateLocator

xtick_locator = AutoDateLocator()
xtick_formatter = AutoDateFormatter(xtick_locator)

ax = plt.axes()
ax.xaxis.set_major_locator(xtick_locator)
ax.xaxis.set_major_formatter(xtick_formatter)
Run Code Online (Sandbox Code Playgroud)

编辑

要与多个子图一起使用,请使用多个定位符/格式化程序对:

import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateFormatter, AutoDateLocator, date2num

x = [datetime.datetime.now() + datetime.timedelta(days=30*i) for i in range(20)]
y = np.random.random((20))

xtick_locator = AutoDateLocator()
xtick_formatter = AutoDateFormatter(xtick_locator)

for i in range(4):
    ax = plt.subplot(2,2,i+1)
    ax.xaxis.set_major_locator(xtick_locator)
    ax.xaxis.set_major_formatter(xtick_formatter)
    ax.plot(date2num(x),y)


plt.show()
Run Code Online (Sandbox Code Playgroud)