Mark K
Mark K

Reputation: 9376

matplotlib to show x-axis with custom date formats and interval

Using matplotlib and mpl_finance to plot candlesticks. Data is in csv AAPL.

enter image description here

I want to show the x-axis as year and month only, i.e."yyyy-mmm", so:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_finance import candlestick2_ohlc
import matplotlib.dates as mdates

data = pd.read_csv('C:\\AAPL.csv', delimiter = "\t")

data = data.sort_values(['Date'], ascending=True)
data = data.tail(100)

fig = plt.figure(figsize=(6,4))
plt.ylim(60, 200)
ax1 = fig.add_subplot(111)

cl =candlestick2_ohlc(ax=ax1,opens=data['Open'],highs=data['High'],lows=data['Low'],closes=data['Close'],width=0.6)

ax1.set_xticks(np.arange(len(data)))
ax1.set_xticklabels(data['Date'], fontsize=10, rotation=90)

# every month of the year like 2008-Jan, 2008-Feb...
locator = mdates.MonthLocator()  
fmt = mdates.DateFormatter('%Y-%b')

X = plt.gca().xaxis
X.set_major_locator(locator)
X.set_major_formatter(fmt)

plt.show()

It doesn't show anything.

Also tried below but doesn't work neither:

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())

enter image description here

How can I have the x-axis only show the year and month??

Thank you.

Upvotes: 2

Views: 2261

Answers (1)

Vinod Sawant
Vinod Sawant

Reputation: 623

Try following solution,

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates

data = pd.read_csv('C:\AAPL.csv')

data = data.sort_values(['Date'], ascending=True)
data = data.tail(100)

from matplotlib.dates import date2num, DayLocator, DateFormatter
data['Date'] = date2num(pd.to_datetime(data['Date']).tolist())

fig, ax=plt.subplots(figsize=(10, 10))
candlestick_ohlc(ax, data.as_matrix(),width=0.6)
ax.set(xlabel='AAPL')
ax.xaxis.set_major_locator(DayLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%b'))
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=4))
plt.show()

Note: I have used candlestick_ohlc instead of candlestick2_ohlc.

Output :

enter image description here

Upvotes: 3

Related Questions