Ordering and Formatting Dates on X-Axis in Seaborn Bar Plot

前端 未结 1 532
予麋鹿
予麋鹿 2021-01-18 05:11

This seems so simple, but for the life of me I can\'t figure it out.

I am new to Python and Seaborn, and I am doing all this online at PythonAnywhere.

All I

相关标签:
1条回答
  • 2021-01-18 05:36

    Using your second approach, simply sort and reformat the datetime values to YYYY-MM-DD and pass values into set_xticklabels. Below demonstrates with random, seeded data:

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    import seaborn as sns
    
    # RANDOM DATA
    np.random.seed(62918)
    emp = pd.DataFrame({'uniqueClientExits': [np.random.randint(15) for _ in range(50)],
                        '12monthsEnding': pd.to_datetime(
                                              np.random.choice(
                                                  pd.date_range('2018-01-01', periods=50), 
                                              50)
                                          )
                       }, columns = ['uniqueClientExits','12monthsEnding'])
    
    # PLOTTING
    fig, ax = plt.subplots(figsize = (12,6))    
    fig = sns.barplot(x = "12monthsEnding", y = "uniqueClientExits", data = emp, 
                      estimator = sum, ci = None, ax=ax)
    
    x_dates = emp['12monthsEnding'].dt.strftime('%Y-%m-%d').sort_values().unique()
    ax.set_xticklabels(labels=x_dates, rotation=45, ha='right')
    

    To check graph output, run a groupby().sum():

    print(emp.groupby('12monthsEnding').sum().head())
    
    #                 uniqueClientExits
    # 12monthsEnding                   
    # 2018-01-01                     12
    # 2018-01-02                      4
    # 2018-01-04                     11
    # 2018-01-06                     13
    # 2018-01-08                     10
    # 2018-01-11                     11
    # 2018-01-14                      9
    # 2018-01-15                      0
    # 2018-01-16                      4
    # 2018-01-17                      5
    # ...
    
    0 讨论(0)
提交回复
热议问题