在matplotlib蜡烛图上标注内容

1 投票
1 回答
938 浏览
提问于 2025-04-18 00:38

下面这段代码是在创建一个蜡烛图,里面有4个价格柱。代码中“NOT WORKING”标签之间的部分是想在第二个价格柱上标注一个“BUY”的字样,位置是根据变量d(x轴)和h(y轴)存储的坐标来确定的。不过,这段代码没有成功,因为图表上没有显示出这个标注。

下面的代码是可以运行的,有人能告诉我怎么在这样的图表上添加标注吗?

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

附注:如果在代码中加入print "(", d, ",", h, ")",会输出以下内容:>>> ( 734543.0 , 1.3292 )。这个点正是我想放箭头的地方,所以我猜问题可能出在箭头的可视化上,而不是它的创建。

1 个回答

1

你的问题是,箭头实际上超出了matplotlib的显示范围。你把xytext的位置设置为(d-1, h+0.5),这个位置远远超出了你的y-limits。下面的代码可以修复你的问题:

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

撰写回答