python - 在 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()
解决方案
关于日期日期标签:您可以在旋转命令中分配刻度对齐,如本文所示。
要缩小标签,您有两种选择:
选项 A:导入matplotlib.dates
以访问DateFormatter
并选择导致较小标签的格式。(例如,省略年份或其他内容)。然后,您还可以使用定位器以不同的方式分隔标签。
选项 B:使用rc_params
ortick_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')
推荐阅读
- wordpress - 如何将自定义字段添加到我的页眉
- typescript - 打字稿扩展第三方类错误:ElementHandle 仅引用类型,但在此处用作值
- flask - kubernetes 入口 websockets (socket.io)
- python - Python,检查电子邮件是否存在
- python - Matplotlib 在绘图内添加网格线
- excel - 如何只需按一下按钮即可将多个不同的单元格复制到另一个工作表
- c++ - C ++无法打印已经创建并从文本文件中读取的整个列表
- django - 如何从 HTML 标签传递值(除了tag ) 来查看使用窗体?
- javascript - 通过 Object.assign 设置 CSS 自定义属性
- ios - Xcode 11.2.1;iOS 13.0 - 有时仅在一部 iPhone 上的现有链接上出现 404 错误 - 在所有其他 iPhone 上都可以正常工作