如何使用matplotlib在x轴上针对特定日期绘制数据

Kit*_*Kit 17 python date matplotlib

我有一个由日期 - 值对组成的数据集.我想在条形图中绘制它们,并在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)]
Run Code Online (Sandbox Code Playgroud)

这是一个使用的可运行代码示例 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()
Run Code Online (Sandbox Code Playgroud)

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

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

Joe*_*ton 30

你正在做的很简单,只使用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()
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢条形图,请使用plt.bar().要了解如何设置线条和标记样式,请参阅标记位置的带有日期标签的绘图http://www.geology.wisc.edu/~jkington/matplotlib_date_labels.pngplt.plot()