代码之家  ›  专栏  ›  技术社区  ›  Kernel

matplotlib ticker functformatter

  •  0
  • Kernel  · 技术社区  · 7 年前

    我正在尝试手动设置条形图的滴答器。我正在使用FunFormatter函数。然而,我发现风趣大师的行为太奇怪了。对于从0到91的X轴范围,我发现FunFormmater返回以下结果。。。知道它是怎么工作的吗。 这是你的名字 link for the data file 提前谢谢

    0 20 30 50 60 80 100 28.805725806451605 41.22463709677419 47.128709677419344 48.55383064516128 51.20048387096774 53.439959677419345 53.03278225806451 53.643548387096764 64.63733870967741 76.85266129032257 83.16391129032257

    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 回复  |  直到 7 年前
        1
  •  3
  •   ImportanceOfBeingErnest    7 年前

    只显示每十个标签是有点危险的 等间距的数据,因为你不知道中间会发生什么。

    不过,要运行脚本,您当然需要确定位置 xx 是数组的有效索引。例如,位置 100

    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