2

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the knowledge! let me try to adapt it to candlestick2_ohlc. :)
No matter how much I use matplotlib, there's always something new to learn. Great solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.