matplotlib收录器FuncFormatter

时间:2018-10-20 02:39:47

标签: python python-2.7 datetime matplotlib

我正在尝试为条形图手动设置股票行情。我正在使用FunFormatter函数。但是,我发现FunFormmater的行为太奇怪了。对于从0到91的X轴范围,我发现FunFormmater返回以下内容...任何想法它是如何工作的。 这是link for the data file 预先感谢

-10.0 0.0 10.0 20.0 30.0 40.0 50.0 60.0 70.0 80.0 90.0 100.0 28.805725806451605 38.374395161290316 41.22463709677419 47.128709677419344 48.55383064516128 49.36818548387095 51.20048387096774 52.42201612903225 53.439959677419345 53.439959677419345 53.03278225806451 53.643548387096764 56.08661290322579 59.75120967741935 64.63733870967741 70.54141129032257 76.85266129032257 83.16391129032257 95.58282258064514

import numpy as np
import matplotlib.pyplot as plt
import pandas as p
import matplotlib.mlab as m
import matplotlib
import matplotlib.ticker as ticker

file1=np.load('numofdays.npz')
fig,axes=plt.subplots(ncols=1)
ax=axes
x=np.arange(len(file1['arr_0']))
y=np.array(file1['arr_0'])
ax.bar(x,y)
mydates=p.DatetimeIndex(file1['arr_1'])

def mme(xx,pos=None):
    print(xx)
#    print(mydates[int(xx-9)].strftime('%Y-%m-%d'))
    return mydates[int(xx-9)].strftime('%Y-%m-%d')

ax.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax.xaxis.set_major_formatter(ticker.FuncFormatter(mme))
fig.autofmt_xdate()

1 个答案:

答案 0 :(得分:2)

仅显示十分等距的数据的每个十分之一标签是有点危险的,因为您不知道这之间会发生什么。

但是,要使脚本运行,您当然需要确保位置xx是数组的有效索引。例如。位置100无效,因为您的数组只有92个元素。为此,您可以引入一个条件。

import numpy as np
import matplotlib.pyplot as plt
import pandas as p

import matplotlib.ticker as ticker

file1=np.load('data/numofdays.npz')

fig,ax=plt.subplots(ncols=1)

x=np.arange(len(file1['arr_0']))
y=np.array(file1['arr_0'])
ax.bar(x,y)
mydates=p.DatetimeIndex(file1['arr_1'])

def mme(xx,pos=None):
    if int(xx) in x:
        return mydates[int(xx)].strftime('%Y-%m-%d')
    else:
        return ""

ax.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax.xaxis.set_major_formatter(ticker.FuncFormatter(mme))
fig.autofmt_xdate()
plt.show()

enter image description here

或者,我当然会考虑绘制实际日期。

import numpy as np
import matplotlib.pyplot as plt
import pandas as p

file1=np.load('data/numofdays.npz')

fig,ax=plt.subplots(ncols=1)

y=np.array(file1['arr_0'])

mydates = p.DatetimeIndex(file1['arr_1'])

ax.bar(mydates,y, width=60)

fig.autofmt_xdate()
plt.show()

enter image description here