【问题标题】:Tkinter: How to adjust dates along x axis?Tkinter:如何沿 x 轴调整日期?
【发布时间】:2013-11-19 14:19:01
【问题描述】:

我一直在修改一个函数,它接受一个 DataFrame(它有一个日期时间的索引),然后选择一列并将其变成一个系列,然后绘制它。一切似乎都很好,但我无法正确显示日期。我希望 x 轴按周而不是按数据点打勾。

    class App: 
        def __init__(self,master, df): 
            frame = Frame(master) 
            frame.pack() 


            series = df['Daily  T'].cumsum()

            self.f = Figure(figsize=(12,6), dpi=100, linewidth=2) 
            self.a = self.f.add_subplot(111) 
            self.a.grid(True) 
            self.a.set_xlabel("DATES")
            self.a.plot(series, 'r-o') 

            self.a.set_xticks(range(len(series)))

            self.a.set_xticklabels([datetime.strftime(date, '%x') for date in series.index])

            self.f.autofmt_xdate()


            self.canvas = FigureCanvasTkAgg(self.f, master=child_win_plot) 
            self.canvas.show() 
            self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) 





    app=App(child_win_plot, filtered_df) 

我不确定应该改变什么。

【问题讨论】:

    标签: python-2.7 matplotlib plot tkinter pandas


    【解决方案1】:

    我无法测试,但是这个怎么样

    # range(0,len(series),7) give (0,7,14,21)
    self.a.set_xticks(range(0,len(series),7)) 
    

    和空字符串的日期

    # empty string in place of some dates 
    # [date, '', '', '', '' , '', '', '' , date ...]
    xlabels = [ datetime.strftime(date, '%x') if index%7 == 0 else '' for index, date in enumerate(series.index)]
    self.a.set_xticklabels(xlabels)
    

    或只有日期 - 没有空字符串

    xlabels = [ datetime.strftime(date, '%x') for index, date in enumerate(series.index) if index%7 == 0 ]
    self.a.set_xticklabels(xlabels)
    

    【讨论】:

    • 第一个解决方案无效,第二个解决方案有效。此外, enumerate 的拼写略有错误。除此之外,它工作得很好,谢谢!
    • enumarate :) 你是对的。我直接在这里写代码 - 我没有 matplotlib 来测试它。
    猜你喜欢
    • 1970-01-01
    • 2016-07-29
    • 2021-04-03
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2016-02-29
    相关资源
    最近更新 更多