pyplot, why isn't the x-axis showing?

前端 未结 1 1610
一向
一向 2021-01-28 19:18

I\'m trying to plot some values against date. However, unfortunately i\'m not getting any values in the x Axis. I feel that this could be due to two factors:

  1. The v
1条回答
  •  孤独总比滥情好
    2021-01-28 19:29

    If you want to control the major and minor ticks locations and formats you will need to use date tickers. Here is a function I regularly use for plot time series that span multiple months:

    def format_xaxis(fig):
         # here I am setting the major ticks to each decade
         # Change to something appropriate for your data
         major= dates.MonthLocator(bymonthday=1)
    
         #Here I am setting each minor ticks to mid-decade 
         # Change to something appropriate for your data    
         minor=dates.MonthLocator(bymonthday=15)
    
         #Here I am setting each major ticks and minor tick formatting
         # Change to something appropriate for your data 
         #look at http://strftime.org/ for other options
         majorfmt = dates.DateFormatter('%B')
         minorfmt = dates.DateFormatter('%d')
    
         # Set the locators and formats for all of the subplots axes
         [i.xaxis.set_major_locator(major) for i in fig.axes]
         [i.xaxis.set_minor_locator(minor) for i in fig.axes]
         [i.xaxis.set_major_formatter(majorfmt) for i in fig.axes]
         [i.xaxis.set_minor_formatter(minorfmt) for i in fig.axes]
    
         # Here I am offsetting the major ticks down so they dont overlap with minor tick lables
         [i.get_xaxis().set_tick_params(which='major', pad=15) for i in fig.axes]
    
         #make them look nice
         for t in fig.axes:
             for tick in t.xaxis.get_major_ticks():
                 tick.label1.set_horizontalalignment('center')
             for label in t.get_xmajorticklabels() :
                 label.set_rotation(0)
                 label.set_weight('bold')
             for label in t.xaxis.get_minorticklabels():
                 label.set_fontsize('small')   
    

    You can swap out dates.MonthLocator for any locator appropriate for your data. Just look at the link I provided.

    A little example:

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.dates as dates
    import numpy as np
    
    df = pd.DataFrame({'Date':pd.date_range(start = '2015-01-01', end = '2015-05-01'), 'TotalDeepSleep':np.random.randint(0,140,size=121)})
    
    
    fig,ax = plt.subplots()
    ax.plot_date(df['Date'], df['TotalDeepSleep'])
    
    format_xaxis(fig)
    

    0 讨论(0)
提交回复
热议问题