Seaborn 条形图中 X 轴上的日期排序和格式化

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

这看起来很简单,但我一辈子都弄不明白。

我是 Python 和 Seaborn 的新手,我正在 PythonAnywhere 在线完成所有这些工作。

我想做的就是在 seaborn 中创建一个简单的条形图,日期在 x 轴上正确排序(即从左到右升序)。

当我尝试这个时:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
import pandas as pd
import seaborn as sns

emp = pd.DataFrame([[32, "5/31/2018"], [3, "2/28/2018"], [40, "11/30/2017"], [50, "8/31/2017"], [51, "5/31/2017"]], 
               columns=["jobs", "12monthsEnding"])

fig = plt.figure(figsize = (10,7))

sns.barplot(x = "12monthsEnding", y = "uniqueClientExits", data = emp, 
estimator = sum, ci = None)

fig.autofmt_xdate()
plt.show()

我明白了:

Nice looking bar graph but with the dates ordered descending from left to right

然后当我尝试将对象转换为日期时间时:

(注意:我在下面使用 pd.to_datetime() 来尝试重现当我在 pd.read_csv() 中使用 parse_dates 时发生的情况,这就是我的方式'我实际上正在创建数据框。)

emp = pd.DataFrame([[32, pd.to_datetime("5/31/2018")], [3, pd.to_datetime("2/28/2018")], [40, pd.to_datetime("11/30/2017")], [50, pd.to_datetime("8/31/2017")], [51, pd.to_datetime("5/31/2017")]], 
               columns=["jobs", "12monthsEnding"])

fig = plt.figure(figsize = (10,7))

sns.barplot(x = "12monthsEnding", y = "uniqueClientExits", data = emp, 
estimator = sum, ci = None)

fig.autofmt_xdate()

plt.show()

我明白了:

Bar plot with the dates in the right order, but WRONG format

我得到了相同的条形图,日期顺序正确,但采用完整的长日期时间格式,带有时间等。但我想要的只是 day/month/year。

我已经搜索了 Whosebug 两天了,但没有任何效果。我开始怀疑部分原因是否是因为我在 PythonAnywhere 上工作。但我也找不到任何原因。

这让我抓狂。期待任何帮助。谢谢

使用第二种方法,只需将日期时间值排序并重新格式化为 YYYY-MM-DD,然后将值传递给 set_xticklabels。下面使用随机种子数据进行演示:

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')

要检查图形输出,运行 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
# ...