X 轴包含负整数时奇怪的 matplotlib 行为

Strange matplotlib behaviour when X axis contains negative integers

我正在尝试绘制一个条形图,其中 X 轴是事件发生的天数(即 t-10、t-9、...、t+10)。下面是 X 轴包含正整数的示例。图表生成正确。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 1, figsize=(12, 8), sharex=True)
x = pd.DataFrame(np.random.normal(0., 1., size=(250, 2)), columns=['X', 'Y'])
x.plot.bar(y=['X'], width=1, ax=axes[0])
x.plot.bar(y=['Y'], width=1, ax=axes[1])
axes[1].set_xticks(x.index[::5])
axes[1].set_xticklabels(x.index[::5])
plt.tight_layout()
plt.show()
plt.clf()

但是,当 X 轴包含负值时,图表显示不正确。知道为什么会这样吗?请注意,我所做的更改只是将 index=[i for i in range(-100, 150)] 添加到 DataFrame。

fig, axes = plt.subplots(2, 1, figsize=(12, 8), sharex=True)
x = pd.DataFrame(np.random.normal(0., 1., size=(250, 2)), columns=['X', 'Y'], index=[i for i in range(-100, 150)])
x.plot.bar(y=['X'], width=1, ax=axes[0])
x.plot.bar(y=['Y'], width=1, ax=axes[1])
axes[1].set_xticks(x.index[::5])
axes[1].set_xticklabels(x.index[::5])
plt.tight_layout()
plt.savefig(f'images/{label}_first_term_struct.png', dpi=300)
plt.clf()

问题在于您设置刻度线的命令。似乎通过 pandas 绘图不会自动使用 x 轴的索引。您可以直接绘制 matplotlib,正如@JohanC 在对您的问题的评论中所建议的那样,或者您可以根据 x 的长度进行索引。这是一种可能的方法:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def do_plot(x, N):
    fig, axes = plt.subplots(2, 1, figsize=(12, 8), sharex=True)
    x.plot.bar(y=['X'], width=1, ax=axes[0])
    x.plot.bar(y=['Y'], width=1, ax=axes[1])
    axes[1].set_xticks(np.arange(N)[::5])
    axes[1].set_xticklabels(x.index[::5])
    plt.tight_layout()

N = 250
m = -100
x = pd.DataFrame(np.random.normal(0., 1., size=(N, 2)),
                 columns=['X', 'Y'],
                 index=[i for i in range(m, N+m)])
do_plot(x, N)