简体   繁体   中英

How can I change my x-axis ticks to show every date on my x-axis in my chart?

I downloaded Bitcoin price data and I want to plot the results. This is my code to retrieve price data:

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()

My code for plotting my results looks like this:

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')

For better visualization, it would be better if all dates are displayed on the x axis.

I tried plt.xticks(price.index) , but unfortunately that does not work. Can somebody help me out to show every date of the data frame on the x-axis?

The output of my code looks like the attached image.

在此处输入图片说明

Try this:

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

As per the documentation you can provide the index and the labels.

在此处输入图片说明

To display dates without time:

date_labels = price.index.map(lambda t: t.strftime('%Y-%m-%d'))
plt.xticks(price.index, labels = date_labels, rotation=45)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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