首页 > 解决方案 > 在 MatplotLib 中调整 X 轴上的日期和修复图例

问题描述

我想知道如何在这里调整我的日期,使它们更小,更适合输出。我尝试过旋转,但它们看起来就像在图表下方漫无目的地浮动。我也想让这个图例要么有一次y_pred,要么有y_test一次,它不会与我的图表重叠。

这些子图是通过循环添加的,并且不会总是相同数量的循环。作为参考, no_splits 将确定通过该TimeSeriesSplit方法运行的循环数。我已经删除了很多不相关的代码,所以更容易理解

这是我的代码:

fig = plt.figure()
    tscv = TimeSeriesSplit(n_splits=self.no_splits)
    for train_index, test_index in tqdm(tscv.split(X)):
        X_train, X_test = X.iloc[train_index], X.iloc[test_index]
        y_train, y_test = y.iloc[train_index], y.iloc[test_index]

        # predict y values
        y_pred = self.regressor.predict(X_test)


        # plot y_pred vs y_test
        y_df = pd.DataFrame(index= X_test_index)
        y_pred = y_pred.reshape(len(y_pred), )
        y_test = y_test.reshape(len(y_test), )
        y_df['y_pred'] = y_pred
        y_df['y_test'] = y_test

        ax = fig.add_subplot(int(sqrt(self.no_splits)), int(sqrt(self.no_splits)+1), i)


        y_df.plot(title = 'Split{}'.format(i), ax=ax, legend=False)
        ax.tick_params(axis='x', rotation=45)

        plt.figlegend()
    plt.subplots_adjust(wspace=0, hspace=0)
    plt.show()

在此处输入图像描述

在此处输入图像描述

标签: pythonpython-3.xmatplotlib

解决方案


关于日期日期标签:您可以在旋转命令中分配刻度对齐,如本文所示。

要缩小标签,您有两种选择:

选项 A:导入matplotlib.dates以访问DateFormatter并选择导致较小标签的格式。(例如,省略年份或其他内容)。然后,您还可以使用定位器以不同的方式分隔标签。

选项 B:使用rc_paramsortick_params来定义字体大小、系列等。这篇文章应该可以帮助您入门。

如您所见,网上应该有很多材料可以帮助您前进...

关于传说

您可以使用 将绘图设置为没有图例条目plt.plot(x, y, label='_nolabel')。例如,您可以将其与 for 循环结合使用,仅在第一次迭代时绘制标签。

for i, (train_index, test_index) in enumerate(tqdm(tscv.split(X))):
    if i==0:
        plt.plot(x, y, label=label)
    else:
        plt.plot(x, y, label='_nolabel')

推荐阅读