gpt4 book ai didi

python - Seaborn tsplot 不能很好地在 x 轴上显示日期时间

转载 作者:太空狗 更新时间:2023-10-29 17:25:07 26 4
gpt4 key购买 nike

下面我有以下脚本,它创建了一个简单的时间序列图:

%matplotlib inline
import datetime
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

df = []
start_date = datetime.datetime(2015, 7, 1)
for i in range(10):
for j in [1,2]:
unit = 'Ones' if j == 1 else 'Twos'
date = start_date + datetime.timedelta(days=i)

df.append({
'Date': date.strftime('%Y%m%d'),
'Value': i * j,
'Unit': unit
})

df = pd.DataFrame(df)

sns.tsplot(df, time='Date', value='Value', unit='Unit', ax=ax)
fig.autofmt_xdate()

结果如下:

enter image description here

如您所见,x 轴的日期时间数字很奇怪,而不是 matplotlib 和其他绘图实用程序附带的常见“漂亮”表示法。我已经尝试了很多东西,重新格式化数据,但它永远不会干净。有人知道解决办法吗?

最佳答案

Matplotlib 将日期表示为 float (以天为单位),因此除非您(或 pandas 或 seaborn)告诉它您的值表示日期,否则它不会将刻度格式化为日期。我不是 seaborn 专家,但看起来它(或 pandas)确实将 datetime 对象转换为 matplotlib 日期,但随后没有为轴分配适当的定位器和格式化程序。这就是为什么您会得到这些奇怪的数字,它们实际上就是自 0001.01.01 以来的日子。因此,您必须手动处理滴答声(在大多数情况下,这会更好,因为它可以让您更好地控制)。

所以你必须分配一个date locator ,决定在哪里放置刻度,以及 date formatter ,然后将格式化刻度标签的字符串。

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

# build up the data
df = []
start_date = datetime.datetime(2015, 7, 1)
for i in range(10):
for j in [1,2]:
unit = 'Ones' if j == 1 else 'Twos'
date = start_date + datetime.timedelta(days=i)

# I believe it makes more sense to directly convert the datetime to a
# "matplotlib"-date (float), instead of creating strings and then let
# pandas parse the string again
df.append({
'Date': mdates.date2num(date),
'Value': i * j,
'Unit': unit
})
df = pd.DataFrame(df)

# build the figure
fig, ax = plt.subplots()
sns.tsplot(df, time='Date', value='Value', unit='Unit', ax=ax)

# assign locator and formatter for the xaxis ticks.
ax.xaxis.set_major_locator(mdates.AutoDateLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y.%m.%d'))

# put the labels at 45deg since they tend to be too long
fig.autofmt_xdate()
plt.show()

结果:

enter image description here

关于python - Seaborn tsplot 不能很好地在 x 轴上显示日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31255815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com