将日期代码添加到 matplotlib/python 图表 [英] Add date tickers to a matplotlib/python chart

查看:74
本文介绍了将日期代码添加到 matplotlib/python 图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个听上去很简单的问题,但这使我发疯了几天.我有一个封闭的历史时间序列,分为两个列表:第一个列表包含价格,比方说P = [1,1.5,1.3 ...],而第二个列表包含相关日期,比方说D = [01/01/2010,02/01/2010 ...].我想做的是绘制这些日期中的一些(当我说一些"时,是因为到目前为止我得到的最佳"结果是将所有这些都显示为代码,因此在x轴)在放大时会显示更多详细信息.这张图片现在具有Matplotlib制作的渐进式自动范围:

I have a question that sounds simple but it's driving me mad for some days. I have a historical time series closed in two lists: the first list is containing prices, let's say P = [1, 1.5, 1.3 ...] while the second list is containing the related dates, let's say D = [01/01/2010, 02/01/2010...]. What I would like to do is to plot SOME of these dates (when I say "some" is because the "best" result I got so far is to show all of them as tickers, so creating a black cloud of unreadable data in the x-axis) that, when you zoom in, are shown more in details. This picture is now having the progressive automated range made by Matplotlib:

而不是 0、200、400 等.我希望绘制与数据点相关的日期值.此外,放大时会看到以下内容:

Instead of 0, 200, 400 etc. I would like to have the dates values that are related to the data-point plotted. Moreover, when I zoom-in I get the following:

除了我得到0到200之间的详细信息(20、40等)之外,我还希望将日期附加到列表中.我确信这是一个简单的问题,但对于Matplotlib和Python来说我还是新手,任何提示都将不胜感激.预先感谢

As well as I get the detail between 0 and 200 (20, 40 etc.) I would like to get the dates attached to the list. I'm sure this is a simple problem to solve but I'm new to Matplotlib as well as to Python and any hint would be appreciated. Thanks in advance

推荐答案

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

Matplotlib has sophisticated support for plotting dates. I'd recommend the use of AutoDateFormatter and AutoDateLocator. They are even locale-specific, so they choose month-names according to your locale.

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)

编辑

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

For use with multiple subplots, use multiple locator/formatter pairs:

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()

这篇关于将日期代码添加到 matplotlib/python 图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆