我如何更改我的x轴刻度,以在图表中的x轴上显示每个日期?

问题描述 投票:0回答:1

我下载了比特币价格数据,我想绘制结果。这是我的检索价格数据的代码:

import requests
periods = '86400'

resp = requests.get('https://api.cryptowat.ch/markets/bitfinex/btcusd/ohlc', params={'periods': periods})

data = resp.json()
df = pd.DataFrame(data['result'][periods], columns=[
    'CloseTime', 'OpenPrice', 'HighPrice', 'LowPrice', 'ClosePrice', 'Volume', 'NA'])

df['CloseTime'] = pd.to_datetime(df['CloseTime'], unit='s')
df.set_index('CloseTime', inplace=True)

#filter df by date until 1 month ago
df1 = df['2019-11-12':'2019-12-11']
price = df1[['ClosePrice']].copy()

用于绘制结果的代码如下:

import matplotlib.pyplot as plt

price['ClosePrice'].plot(figsize=(14, 7), color = 'blue')
plt.grid(b=True, which='both', color='#666666', linestyle='-')
plt.ylabel('Price')
plt.title('Bitcoin price')

为了获得更好的可视化效果,最好将所有日期都显示在x轴上。

我尝试过plt.xticks(price.index),但不幸的是,这不起作用。有人可以帮我在x轴上显示数据框的每个日期吗?

我的代码输出看起来像附件的图像。

enter image description here

python matplotlib charts axis bitcoin
1个回答
0
投票

尝试一下:

plt.xticks(price.index, price.index, rotation=45)

根据documentation,您可以提供索引标签。

enter image description here

要显示没有时间的日期:

date_labels = price.index.map(lambda t: t.strftime('%Y-%m-%d'))
plt.xticks(price.index, labels = date_labels, rotation=45)
© www.soinside.com 2019 - 2024. All rights reserved.