减少时间序列数据xaxis的时间频率

2024-04-28 22:03:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用10年的数据绘制一家特定公司的股票价格。但x轴上充满了大量不可读的数据。我尝试了许多方法来降低x轴频率。 我不想偏离x轴,而是很乐意每半年只显示一次刻度。 下面是我的代码。请帮我弄到想要的图

plt.figure(figsize=(25,5))
plt.plot(amd_df['date'][:train_seq],amd_df['close'][:train_seq],color='b',label = 'Train Data')
plt.plot(amd_df['date'][train_seq:],amd_df['close'][train_seq:],color='r',label = 'Test Data')
plt.title('AMD Stock Price')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.xticks( rotation=25 )
plt.legend()
plt.show()

我们在这个图中有大约2683个数据点。 请看下面。 enter image description here 多谢各位


Tags: 数据dfclosedatadateplotstock绘制
1条回答
网友
1楼 · 发布于 2024-04-28 22:03:41

没有提供任何数据,所以我们用随机数创建样本数据。关键是设置MOnthLocator(interval=6)并将其设置为Dateformatter()。见官方报告

import pandas as pd
import numpy as np

date_rng = pd.date_range('2010-01-01','2020-01-01', freq='B')
val = np.random.randint(0,100,(2609))
amd_df = pd.DataFrame({'date':date_rng,'close':val})
amd_df['date'] = pd.to_datetime(amd_df['date'])
train_seq = 2500
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig = plt.figure(figsize=(25,5))
ax = fig.add_subplot(111)

ax.plot(amd_df['date'][:train_seq],amd_df['close'][:train_seq],color='b',label = 'Train Data')
ax.plot(amd_df['date'][train_seq:],amd_df['close'][train_seq:],color='r',label = 'Test Data')
ax.set_title('AMD Stock Price')
ax.set_xlabel('Date')
ax.set_ylabel('Stock Price')

months = mdates.MonthLocator(interval=6)
months_fmt = mdates.DateFormatter('%y-%m')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)

ax.legend()
plt.show()

enter image description here

相关问题 更多 >