为什么matplotlib的tight_layout会更改我的xticklabel?

时间:2019-06-03 17:41:37

标签: pandas matplotlib

这是一个最小的工作示例:

import pandas as pd
import matplotlib.pyplot as plt

ex2 = pd.DataFrame.from_dict({'values': {'2019-05-16': -0.4539503789160822,
  '2019-05-17': 0.17824705254564818,
  '2019-05-18': -0.8145004682381226,
  '2019-05-19': -0.16068367742158898,
  '2019-05-20': -0.14703503546059876,
  '2019-05-21': 0.4063766692521381,
  '2019-05-22': -0.9572965166800591,
  '2019-05-23': -0.7125760201598659,
  '2019-05-24': 0.5195104837966258,
  '2019-05-25': 0.5763244454664754,
  '2019-05-26': 0.7512143968738716,
  '2019-05-27': 0.9708304482205082,
  '2019-05-28': 0.910905683484745,
  '2019-05-29': -0.19652191338402258,
  '2019-05-30': -0.7913575644422205,
  '2019-05-31': 0.406385536323757,
  '2019-06-01': -0.9636746362006964,
  '2019-06-02': -0.6904113830684114,
  '2019-06-03': -0.4015962383225227}})

以下代码按预期工作:

fig, ax = plt.subplots(figsize=(12, 8))
ex2.plot(ax=ax)

working as expected

但是,只做简单的事情而仅添加tight_layout命令就会以这种奇怪的方式破坏它:

fig, ax = plt.subplots(figsize=(12, 8))
ex2.plot(ax=ax)
fig.tight_layout()

xticklabels are now incorrect

这似乎是一个错误,但如果不是这样,我将不胜感激。

我正在使用以下版本:

matplotlib version: 3.1.0
python version: 3.6.8
pandas version: 0.24.2

编辑

通过以下方式将索引更改为datetime

ex2.index = pd.to_datetime(ex2.index)

然后重新运行以上两段代码,可以得到一致的结果(在这种情况下)。

fig, ax = plt.subplots(figsize=(12, 8))
ex2.plot(ax=ax)
fig.tight_layout()

correct xticklabels

0 个答案:

没有答案