使用 matplotlib 格式化日期 [英] Date formatting with matplotlib

查看:41
本文介绍了使用 matplotlib 格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Python 2.6.2Matplotlib 1.1.0

Using Python 2.6.2 Matplotlib 1.1.0

基于 http://matplotlib.sourceforge.net/examples/api/date_index_formatter.html ,我已经构建了一个Python程序来生成图像图

Based on http://matplotlib.sourceforge.net/examples/api/date_index_formatter.html, I have built a Python program to generate an image plot

gr = getResults()
AttributeName = gr.getAttributeName(attributeId)
dates = []
values = []
for data in gr.byClient(clientId, attributeId):
    dates.append(data[0])
    values.append(data[1])

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.ticker as ticker
import numpy as np

# Create a figure with size 6 x 6 inches.
fig = Figure(figsize=(6,6))

# Create a canvas and add the figure to it.
canvas = FigureCanvas(fig)

# Create a subplot.
ax = fig.add_subplot(111)

# Set the title.
ax.set_title("Response over time",fontsize=14)

# Set the X Axis label.
ax.set_xlabel("Date",fontsize=12)

# Set the Y Axis label.
ax.set_ylabel(AttributeName,fontsize=12)

# Display Grid.
ax.grid(True,linestyle='-',color='0.75')

N = len(dates)
ind = np.arange(N)

def format_date(x, pos=None):
    thisind = np.clip(int(x+0.5),0, N-1)
    return dates[thisind].strftime('%Y-%m-%d')

ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))

# Generate the Scatter Plot.
ax.scatter(dates,values,s=20,color='tomato');
fig.autofmt_xdate()

# Save the generated Scatter Plot to a PNG file.
canvas.print_figure(outputFileName,dpi=50)

问题出在 format_date 方法中.当它被调用时,x参数具有类似734586、734747、734808的值.这会使clip方法始终将索引设置为最后一个日期.最终图像的实际布局是可以的,只是选择了错误的日期.x 值如何用于选择均匀间隔的日期?

The problem is in the format_date method. When it is called the x parameter has values like 734586, 734747, 734808 ... This causes the clip method to always set the index to the last date. The actual layout of the final image is ok, it is just selecting the wrong date. How is the x value to be used to select evenly spaced dates?

推荐答案

你可以调用 pylab.num2date() 把这个数字转换成 datetime 对象:

You can call pylab.num2date() to convert this numbers into datetime object:

import pylab as pl
from matplotlib import ticker
from datetime import date

dates = [date(2012,7,10), date(2012,8,5), date(2012,9,4)]
values = [1,2,3]

def format_date(x, pos=None):
    return pl.num2date(x).strftime('%Y-%m-%d')

gca().xaxis.set_major_formatter(ticker.FuncFormatter(format_date))

# Generate the Scatter Plot.
scatter(dates,values,s=20,color='tomato');
gcf().autofmt_xdate()

这篇关于使用 matplotlib 格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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