繁体   English   中英

matplotlib中的axes.fmt_xdata未被调用

[英]axes.fmt_xdata in matplotlib not being called

我正在尝试在Django应用程序中格式化我的X轴日期,我在返回响应对象的内存中的图形。 我按照我已在ipython笔记本中使用的相同示例执行此操作:

def pretty_date(date):
    log.info("HELLO!")
    return date.strftime("%c")

def image_calls(request):
    log.info("in image_loadavg")

    datetimes = []
    calls = []
    for m in TugMetrics.objects.all():
        datetimes.append(m.stamp)
        calls.append(m.active_calls)

    plt.plot(datetimes, calls, 'b-o')
    plt.grid(True)
    plt.title("Active calls")
    plt.ylabel("Calls")
    plt.xlabel("Time")

    fig = plt.gcf()
    fig.set_size_inches(8, 6)
    fig.autofmt_xdate()

    axes = plt.gca()
    #axes.fmt_xdata = mdates.DateFormatter("%w %H:%M:%S")
    axes.fmt_xdata = pretty_date

    buf = io.BytesIO()
    fig.savefig(buf, format='png', dpi=100)
    buf.seek(0)
    return HttpResponse(buf, content_type='image/png')

图表被返回,但我似乎无法控制X轴的外观,以及我的HELLO! 永远不会调用日志。 请注意,m.stamp是一个日期时间对象。

这在ipython笔记本中运行良好,都运行matplotlib 1.4.2。

帮助赞赏。

当鼠标悬停在绘图上时, axes.fmt_xdata控制交互显示在工具栏右下角的坐标。 它永远不会被调用,因为你没有使用gui后端制作交互式情节。

你想要的是ax.xaxis.set_major_formatter(formatter) 此外,如果您只是喜欢默认的日期格式化程序,则可以使用ax.xaxis_date()

作为基于代码的快速示例(使用随机数据):

import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

time = mdates.drange(dt.datetime(2014, 12, 20), dt.datetime(2015, 1, 2),
                     dt.timedelta(hours=2))
y = np.random.normal(0, 1, time.size).cumsum()
y -= y.min()

fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(time, y, 'bo-')
ax.set(title='Active Calls', ylabel='Calls', xlabel='Time')
ax.grid()

ax.xaxis.set_major_formatter(mdates.DateFormatter("%w %H:%M:%S"))
fig.autofmt_xdate() # In this case, it just rotates the tick labels

plt.show()

在此输入图像描述

如果你更喜欢默认的日期格式化程序:

import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

time = mdates.drange(dt.datetime(2014, 12, 20), dt.datetime(2015, 1, 2),
                     dt.timedelta(hours=2))
y = np.random.normal(0, 1, time.size).cumsum()
y -= y.min()

fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(time, y, 'bo-')
ax.set(title='Active Calls', ylabel='Calls', xlabel='Time')
ax.grid()

ax.xaxis_date() # Default date formatter
fig.autofmt_xdate()

plt.show()

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM