繁体   English   中英

matplotlib python 数据采用 ymd 格式,但轴标签显示 y 月如何更改

[英]matplotlib python data in ymd format but axis labels show y-month how to change

我的数据如下 83 行 2 列

x1.head()

     x          y
79  2021-01-10  3755
80  2021-01-17  3680
81  2021-01-24  4192
82  2021-01-31  4587
83  2021-02-07  4398

但是当我 plot 它使用

plt.figure(figsize=(15,10))
plt.grid()
plt.plot(x1['x'], x1['y']);

我的 x 轴如下所示 - 采用年月格式。 我想保持与第 x 列相同的格式。

  1. 如何解决?
  2. 为什么它会改变日期格式?
  3. 如何确保我们获得所有 x 轴标签

在此处输入图像描述

尝试使用“DateFormatter”,在其中指定要在轴上显示年、月、日。 例如,您可以只留下年份,看看它是如何工作的。

ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y'))

以下是 x1 列转换为日期的代码,DateFormatter 指定年、月、日。

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates

x1 = pd.DataFrame({'x': ['2021-01-10', '2021-01-17', '2021-01-24', '2021-01-31', '2021-02-07'],
                   'y': [3755, 3680, 4192, 4587, 4398]})

x1['x'] = pd.to_datetime(x1['x'])

fig, ax = plt.subplots()
ax.plot(x1['x'], x1['y'])
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM