当我尝试格式化日期时,轴刻度标签消失了

时间:2019-02-04 18:51:37

标签: pandas datetime matplotlib seaborn

以下代码在绘制热图时工作正常

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as mdates
%matplotlib inline

# Make test dataframe
df = pd.DataFrame(np.random.rand(20,61),
                  index=np.arange(20),
                  columns=pd.date_range(start='2012-03-01', end='2012-04-30', freq='d'))

# Plot it
fig, ax = plt.subplots(1,1,figsize=[10,5])
sns.heatmap(df, ax=ax, cmap='inferno', cbar=None)

# Check that x axis is labeled
ax.xaxis.get_ticklabels()

返回: <a list of 31 Text major ticklabel objects> enter image description here

但是,当我尝试添加格式程序时,整个x轴都消失了,

...
# Adding this to the above code seems to switch off the X axis
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d%m%Y'))

# And now my ticklabels are gone
ax.xaxis.get_ticklabels()

返回: <a list of 0 Text major ticklabel objects> enter image description here

任何人都可以看到问题所在吗?理想情况下,我更喜欢一种自动格式化解决方案(而不是通过手动提供标签列表来覆盖),因为我认为后者可能容易出错,并且我想尝试使用频率和标签格式。我尝试了其他几种答案,但似乎都无法解决问题。

0 个答案:

没有答案