Python/Matplotlib 每个日期都太接近了

Python/Matplotlib dates are too close to each one

我有一个简单的图表,显示一段时间内的比特币价格,您可以在图片上看到。

问题是 x 轴上的日期彼此太接近了。事情是我不需要显示每个日期。我能否以某种方式将它们限制为 6 个标签,而不是 25 个标签,正如您现在在图像上看到的那样。或者有没有更好的方法来处理日期?

我的代码:

def plot_data_out(x: array, y: array):
    x = np.array(x,dtype=datetime)
    y = np.array(y,dtype=float)
    print(x)
    print(y)
    plt.plot(x, y)
    plt.show()

x 数据:

['2022-03-04 01:00:00' '2022-03-04 02:00:00' '2022-03-04 03:00:00'
 '2022-03-04 04:00:00' '2022-03-04 05:00:00' '2022-03-04 06:00:00'
 '2022-03-04 07:00:00' '2022-03-04 08:00:00' '2022-03-04 09:00:00'
 '2022-03-04 10:00:00' '2022-03-04 11:00:00' '2022-03-04 12:00:00'
 '2022-03-04 13:00:00' '2022-03-04 14:00:00' '2022-03-04 15:00:00'
 '2022-03-04 16:00:00' '2022-03-04 17:00:00' '2022-03-04 18:00:00'
 '2022-03-04 19:00:00' '2022-03-04 20:00:00' '2022-03-04 21:00:00'
 '2022-03-04 22:00:00' '2022-03-04 23:00:00' '2022-03-05 00:00:00'
 '2022-03-05 01:00:00']

y 数据

[42454.   41603.36 41510.58 41403.7  41449.93 41379.99 41374.45 41407.98
 41436.98 41590.   41522.29 41676.56 41662.06 41511.3  41315.75 41106.91
 40694.32 40754.41 40840.53 40605.88 39782.13 39469.36 39392.83 39004.73
 39148.65]

您可以将 x 轴数据转换为日期时间格式,然后用它来绘制图形。即便如此,您仍然可以看到标签看起来很拥挤。您可以将标签旋转 30 度并获得更清晰的图表

v = ['2022-03-04 01:00:00','2022-03-04 02:00:00','2022-03-04 03:00:00',
 '2022-03-04 04:00:00','2022-03-04 05:00:00','2022-03-04 06:00:00',
 '2022-03-04 07:00:00','2022-03-04 08:00:00','2022-03-04 09:00:00',
 '2022-03-04 10:00:00','2022-03-04 11:00:00','2022-03-04 12:00:00',
 '2022-03-04 13:00:00','2022-03-04 14:00:00','2022-03-04 15:00:00',
 '2022-03-04 16:00:00','2022-03-04 17:00:00','2022-03-04 18:00:00',
 '2022-03-04 19:00:00','2022-03-04 20:00:00','2022-03-04 21:00:00',
 '2022-03-04 22:00:00','2022-03-04 23:00:00','2022-03-05 00:00:00',
 '2022-03-05 01:00:00']

y = [42454.,41603.36,41510.58,41403.7 ,41449.93,41379.99,41374.45,41407.98,
 41436.98, 41590. ,  41522.29, 41676.56 ,41662.06, 41511.3  ,41315.75, 41106.91,
 40694.32, 40754.41 ,40840.53, 40605.88, 39782.13 ,39469.36 ,39392.83 ,39004.73,
 39148.65]

v1 = [datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S") for x in v]

import matplotlib.pyplot as plt
plt.plot(v1,y)
plt.xticks(rotation = 30)