Center x-axis labels in line plot

前端 未结 3 537
-上瘾入骨i
-上瘾入骨i 2020-12-30 16:45

I am building a line plot with two lines, one for high temperatures and the other for low temperatures. The x-axis is based on days over one complete year in datetime format

3条回答
  •  无人及你
    2020-12-30 17:28

    It often makes sense to use dates directly when plotting. So instead of manually setting fixed locations for the labels, one may use matplotlib.dates locators. To position ticks in the middle of the months, one could choose the 15th of the month,

    matplotlib.dates.MonthLocator(bymonthday=15)
    

    A full example:

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    import matplotlib.ticker as mticker
    import random
    
    df = pd.DataFrame(random.sample(range(10000),8760),
                      index = pd.date_range(start ='2013-01-01 00:00:00',
                                            end ='2013-12-31 23:30:00',
                                            freq='1H'),
                      columns =['value'])
    
    fig, ax = plt.subplots()
    ax.plot(df.index, df['value'])
    ax.set_xlim(pd.Timestamp('2013-01-01 00:00:00'), pd.Timestamp('2013-12-31 23:30:00'))
    
    months = mdates.MonthLocator(bymonth =(1,6,12), bymonthday=15 )
    allmonths = mdates.MonthLocator()
    m_fmt = mdates.DateFormatter('%b')
    ax.xaxis.set_major_locator(allmonths)
    ax.xaxis.set_minor_locator(months)
    
    ax.xaxis.set_major_formatter(mticker.NullFormatter())
    ax.xaxis.set_minor_formatter(m_fmt)
    ax.tick_params(axis="x", which="minor", length=0)
    plt.show()
    

提交回复
热议问题