<p>Matplotlib将日期表示为浮点数(以天为单位),因此,除非您(或pandas或seaborn)告诉它您的值表示日期,否则它不会将刻度设置为日期格式。我不是一个天生的专家,但是看起来它(或者熊猫)确实将<code>datetime</code>对象转换为matplotlib日期,但是没有为轴分配适当的定位器和格式化程序。这就是为什么你会得到这些奇怪的数字,事实上,它们只是0001.01.01之后的几天。因此,您必须手动处理滴答声(在大多数情况下,这是更好的,因为它给您更多的控制)。</p>
<p>因此,您必须指定一个<a href="http://matplotlib.org/api/dates_api.html#date-tickers" rel="noreferrer">date locator</a>,决定在哪里放置记号,以及一个<a href="http://matplotlib.org/api/dates_api.html#matplotlib.dates.DateFormatter" rel="noreferrer">date formatter</a>,然后为记号标签格式化字符串。</p>
<pre><code>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()
</code></pre>
<p>结果:</p>
<p><img src="https://i.stack.imgur.com/1TYQb.png" alt="enter image description here"/></p>