Matteo NNZ
Matteo NNZ

Reputation: 12645

Annotate something on a matplotlib candlestick chart

The following snippet of code is creating a candlestick chart with 4 price bars. The lines of code written between the "NOT WORKING" tags are supposed to annotate the word 'BUY' on the second price bar following the coordinates stored into the variables d (x-axis) and h (y-axis). However, this does not work cause there's no annotation into the chart.

The code below is runnable, can anyone explain me how to make an annotation on a chart like this?

from pylab import * 
from matplotlib.finance import candlestick
import matplotlib.gridspec as gridspec

quotes = [(734542.0, 1.326, 1.3287, 1.3322, 1.3215), (734543.0, 1.3286, 1.3198, 1.3292, 1.3155), (734546.0, 1.321, 1.3187, 1.3284, 1.3186), (734547.0, 1.3186, 1.3133, 1.3217, 1.308)]

fig, ax = subplots()
candlestick(ax,quotes,width = 0.5)
ax.xaxis_date()
ax.autoscale_view()

#NOT WORKING
h = quotes[1][3]
d = quotes[1][0]
ax.annotate('BUY', xy = (d-1,h), xytext = (d-1, h+0.5), arrowprops = dict(facecolor='black',width=1,shrink=0.25))
#NOT WORKING    

plt.show()

P.S. Embedding the statement print "(", d, ",", h, ")" gives the following output: >>> ( 734543.0 , 1.3292 ). That is exactly the point where I would like to get my arrow, so I guess the problem must be related with the visualization of the arrow and not with its creation.

Upvotes: 1

Views: 957

Answers (1)

Ffisegydd
Ffisegydd

Reputation: 53678

Your problem is that your arrow is effectively off the matplotlib screen. You have set the xytext position to (d-1, h+0.5) which is way, way off your y-limits. The following fixes your code:

from pylab import * 
from matplotlib.finance import candlestick
import matplotlib.gridspec as gridspec

quotes = [(734542.0, 1.326, 1.3287, 1.3322, 1.3215), (734543.0, 1.3286, 1.3198, 1.3292, 1.3155), (734546.0, 1.321, 1.3187, 1.3284, 1.3186), (734547.0, 1.3186, 1.3133, 1.3217, 1.308)]

fig, ax = subplots()
candlestick(ax,quotes,width = 0.5)
ax.xaxis_date()
ax.autoscale_view()

#NOT WORKING
h = quotes[1][3]
d = quotes[1][0]
ax.annotate('BUY', xy = (d-1,h), xytext = (d-1, h+0.003), arrowprops = dict(facecolor='black',width=1,shrink=0.25))
#NOT WORKING    

plt.show()

Plot output

Upvotes: 1

Related Questions