简体   繁体   English

在Seaborn Bar Plot中对X轴进行排序和格式化日期

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

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. 我是Python和Seaborn的新手,我在PythonAnywhere在线完成所有这些工作。

All I am trying to do is create a simple barplot in seaborn, with dates ordered properly (that is, ascending from left to right), on the x-axis. 我所要做的就是在seaborn中创建一个简单的条形图,在x轴上正确排序日期(即从左到右上升)。

When I try this: 当我尝试这个:

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

I get this: 我明白了:

Nice looking bar graph but with the dates ordered descending from left to right 看起来不错的条形图,但日期从左到右依次递减

And then when I try to convert the objects to datetime: 然后当我尝试将对象转换为datetime时:

(note: i'm using pd.to_datetime() below in order to try and recreate what happens when I use parse_dates in pd.read_csv(), which is how I'm actually creating the dataframe.) (注意:我正在使用下面的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()

I get this: 我明白了:

Bar plot with the dates in the right order, but WRONG format 条形图,日期顺序正确,但格式错误

I get the same bar plot, with the dates ordered properly, but in the full, long datetime format, with the time, etc. But all I want is the day/month/year. 我得到了相同的条形图,日期排序正确,但是以完整,长日期时间格式,时间等等。但我想要的只是日/月/年。

I've scoured stackoverflow for two days now and nothing has worked. 我已经扫描了stackoverflow两天了,没有任何工作。 I'm starting to wonder if part of the reason is because I'm working on PythonAnywhere. 我开始想知道部分原因是因为我正在使用PythonAnywhere。 But I also can't find any reason why that would be. 但我也找不到任何理由。

This is driving me nuts. 这让我疯了。 Looking forward to any assistance. 期待任何帮助。 Thanks. 谢谢。

Using your second approach, simply sort and reformat the datetime values to YYYY-MM-DD and pass values into set_xticklabels . 使用第二种方法,只需将日期时间值排序并重新格式化为YYYY-MM-DD ,并将值传递给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() : 要检查图形输出,请运行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
# ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM