python - 未调用 matplotlib 中的 axes.fmt_xdata

标签 python django matplotlib

我正在尝试在 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 轴的外观,我的你好!永远不会调用日志。请注意,m.stamp 是一个日期时间对象。

这在运行 matplotlib 1.4.2 的 ipython notebook 中运行良好。

感谢帮助。

最佳答案

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

enter image description here

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

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

enter image description here

关于python - 未调用 matplotlib 中的 axes.fmt_xdata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28533200/

相关文章:

python - 将 django HiddenInput 小部件的值设置为模板中呈现的另一个对象的 id

python - Django将类似字节的对象或数字保存到DB : TypeError: int() argument must be a string,,而不是 'tuple'

python - 用于多张图片上传的django rest框架

python - 从绘图屏幕上单击的两点画线,然后删除艺术家

Python错误加载google API的JSON代码

python - 在谷歌应用引擎上,为什么我的 'import' 语句在 Live 上失败,但在 Dev(localmachine) 上工作?

python - Pandas:使用现有索引和列标题创建 MultiIndex/groupby

javascript - 使用 angularJs 时 Django 表单实例不显示默认值

python - 如何更改 matplotlib 极坐标图 'r' 轴的位置?

python - 如何将散点图转换为曲面图?