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

问题描述 投票:0回答:2

这看起来很简单,但我怎么也想不通。

我是 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。但我也找不到任何理由。

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

python pandas matplotlib seaborn pythonanywhere
2个回答
35
投票

使用第二种方法,只需将日期时间值排序并重新格式化为

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

要检查图形输出,请运行

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
投票

正如洛菲姆在评论中提到的,你可以去:

fig.autofmt_xdate()

这会自动旋转日期,并将数字减少到刻度。

© www.soinside.com 2019 - 2024. All rights reserved.