【问题标题】:How to plot data against specific dates on the x-axis using matplotlib如何使用 matplotlib 在 x 轴上针对特定日期绘制数据
【发布时间】:2011-03-30 00:07:05
【问题描述】:

我有一个由日期值对组成的数据集。我想将它们绘制在条形图中,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:已修复。谢谢,我意识到可能有更多的人可以阅读matplotlib + pyplot,而不是matplotlib + wx

标签: python date matplotlib


【解决方案1】:

你所做的很简单,最简单的方法是使用 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() Plot with date labels at marker locations http://www.geology.wisc.edu/~jkington/matplotlib_date_labels.png

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 2020-06-09
    • 2018-08-31
    相关资源
    最近更新 更多