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

标签 python pandas matplotlib seaborn pythonanywhere

这看起来很简单,但我这辈子都想不通。

我是 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

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

我已经搜索 stackoverflow 两天了,但没有任何效果。我开始怀疑部分原因是否是因为我正在使用 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')

Plot Output

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

关于python - Seaborn 条形图中 X 轴上的日期排序和格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51105648/

相关文章:

python - 使用healpy 和 projplot 进行 Aitoff 投影

python - Seaborn:如何将垂直线添加到分布图 (sns.distplot)

python - 使用python解析相对链接和绝对链接

python - 将嵌套列表转换为 numpy 数组的有效方法

python - 用另一个数据框 pandas 的第一个值填充 0 和 1 系列的数据框

python - 在 pandas apply 方法中,根据条件复制行

python - Scipy/Pylab 错误.. 预计在 : dynamic lookup?

c++ - Boost.Python - 公开一个类

python - django south错误迁移失败

python - Pandas 的数据框划分系列