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

2024-04-19 17:14:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由日期-值对组成的数据集。我想把它们画成一个条形图,在x轴上有具体的日期。

我的问题是matplotlibxticks分布在整个日期范围内;还使用点绘制数据。

日期都是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. 对使用的图形类型(条、线、点等)进行更严格的控制

Tags: 数据对象代码示例datadatetimedatematplotlib
1条回答
网友
1楼 · 发布于 2024-04-19 17:14:48

你所做的很简单,使用plot比plot更容易。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()

如果您喜欢条形图,只需使用^{}。要了解如何设置线条和标记样式,请参见^{}Plot with date labels at marker locations http://www.geology.wisc.edu/~jkington/matplotlib_date_labels.png

相关问题 更多 >