简体   繁体   中英

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

PS 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.

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

绘图输出

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