如何使用matplotlib将数据绘制在特定日期的x轴上?

17

我有一个由日期-数值对组成的数据集。我想在条形图中将它们绘制出来,并在x轴上显示特定的日期。

我的问题是,matplotlib会在整个日期范围内分布xticks,并使用点来绘制数据。

所有的日期都是datetime对象。以下是数据集的样例:

data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123),
        (DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678),
        (DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987),
        (DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)]

这是一个使用pyplot的可运行代码示例。

import datetime as DT
from matplotlib import pyplot as plt

data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123),
        (DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678),
        (DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987),
        (DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)]

x = [date for (date, value) in data]
y = [value for (date, value) in data]

fig = plt.figure()

graph = fig.add_subplot(111)
graph.plot_date(x,y)

plt.show()

问题摘要:
我的情况更像是我已经有一个Axes实例(在上面的代码中引用为graph),我想要做以下事情:

  1. 使xticks对应于确切的日期值。我听说过matplotlib.dates.DateLocator,但我不知道如何创建它,然后将其与特定的Axes对象相关联。
  2. 更精细地控制所使用的图形类型(柱形、线性、点等)。

小贴士:由于您的问题实际上纯粹涉及 matplotlib 并没有涉及 wxWidgets 的任何特定内容,因此如果您修改示例以使用 matplotlib.pyplot 中的函数并将 wx 相关内容排除在外,则可能会使事情变得更容易。 - David Z
@David:已修复。谢谢,我意识到可能有更多人能够更好地阅读matplotlib + pyplot,而不是matplotlib + wx - Kit
1个回答

31

您正在做的事情足够简单,最好只使用plot而不是plot_date。plot_date适用于更复杂的情况,但是可以很容易地完成所需的设置。

例如,根据您上面的示例:

import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num

data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123),
        (DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678),
        (DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987),
        (DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)]

x = [date2num(date) for (date, value) in data]
y = [value for (date, value) in data]

fig = plt.figure()

graph = fig.add_subplot(111)

# Plot the data as a red line with round markers
graph.plot(x,y,'r-o')

# Set the xtick locations to correspond to just the dates you entered.
graph.set_xticks(x)

# Set the xtick labels to correspond to just the dates you entered.
graph.set_xticklabels(
        [date.strftime("%Y-%m-%d") for (date, value) in data]
        )

plt.show()

如果你更喜欢柱状图,只需使用plt.bar()即可。要了解如何设置线条和标记样式,请参见plt.plot()在标记位置处使用日期标签的绘图 http://www.geology.wisc.edu/~jkington/matplotlib_date_labels.png

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