【问题标题】:Ordering and Formatting Dates on X-Axis in Seaborn Bar PlotSeaborn 条形图中 X 轴上的排序和格式化日期
【发布时间】:2018-12-08 21:06:53
【问题描述】:

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

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

这让我发疯了。期待任何帮助。谢谢。

【问题讨论】:

  • @Parfait,感谢您的提示。这是我第一次提出问题,很高兴收到这样的提示。非常感激。我希望我的编辑现在使我的问题可行。

标签: python pandas matplotlib seaborn pythonanywhere


【解决方案1】:

使用第二种方法,只需将日期时间值排序并重新格式化为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
# ...

【讨论】:

  • @Parfait,您能否详细说明您使用的原因:.sort_values().unique()(当我最终使用它时,x 轴不正确,没有它它可以正常工作)。谢谢
  • @adhg - 这取决于您的数据。对于这个随机示例,相同日期有多个值,但 x 轴仅显示唯一日期。
  • 你也可以使用fig.autofmt_xdate()而不是明确提及旋转角度。
  • 这会导致错误 FixedFormatter 只能与 FixedLocator 一起使用
  • @Tasty213,鉴于此解决方案已使用近三年,pandas、seaborn 或 matplotlib 可能在最近的版本中调整了此日期格式功能。
猜你喜欢
  • 2019-10-31
  • 1970-01-01
  • 2020-11-20
  • 2019-02-18
  • 2015-10-26
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多