在X轴上调整日期并在MatplotLib中固定图例

时间:2019-06-13 11:31:27

标签: python python-3.x matplotlib

我想知道如何在这里调整日期,使它们更小,更适合输出。我尝试过旋转,但它们似乎在图表下方无目的地浮动。另外,我想使图例在与我的图表不重叠的某个地方出现y_predy_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()

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

关于日期日期标签:您可以按this post所示在轮换命令中指定刻度线对齐。

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

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

选项B :使用rc_paramstick_params定义字体大小,字体等。This post应该使您入门。

如您所见,应该有很多在线材料来帮助您前进...

关于图例

您可以使用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')
相关问题