- 十八、注解股票图表的最后价格
十八、注解股票图表的最后价格
在这个 Matplotlib 教程中,我们将展示如何跟踪股票的最后价格的示例,通过将其注解到轴域的右侧,就像许多图表应用程序会做的那样。
虽然人们喜欢在他们的实时图表中看到历史价格,他们也想看到最新的价格。 大多数应用程序做的是,在价格的y轴高度处注释最后价格,然后突出显示它,并在价格变化时,在框中将其略微移动。 使用我们最近学习的注解教程,我们可以添加一个bbox。
我们的核心代码是:
bbox_props = dict(boxstyle='round',fc='w', ec='k',lw=1)ax1.annotate(str(closep[-1]), (date[-1], closep[-1]),xytext = (date[-1]+4, closep[-1]), bbox=bbox_props)
我们使用ax1.annotate来放置最后价格的字符串值。 我们不在这里使用它,但我们将要注解的点指定为图上最后一个点。 接下来,我们使用xytext将我们的文本放置到特定位置。 我们将它的y坐标指定为最后一个点的y坐标,x坐标指定为最后一个点的x坐标,再加上几个点。我们这样做是为了将它移出图表。 将文本放在图形外面就足够了,但现在它只是一些浮动文本。
我们使用bbox参数在文本周围创建一个框。 我们使用bbox_props创建一个属性字典,包含盒子样式,然后是白色(w)前景色,黑色(k)边框颜色并且线宽为 1。 更多框样式请参阅 matplotlib 注解文档。
最后,这个注解向右移动,需要我们使用subplots_adjust来创建一些新空间:
plt.subplots_adjust(left=0.11, bottom=0.24, right=0.87, top=0.90, wspace=0.2, hspace=0)
这里的完整代码如下:
import matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.ticker as mtickerfrom matplotlib.finance import candlestick_ohlcfrom matplotlib import styleimport numpy as npimport urllibimport datetime as dtstyle.use('fivethirtyeight')print(plt.style.available)print(plt.__file__)def bytespdate2num(fmt, encoding='utf-8'):strconverter = mdates.strpdate2num(fmt)def bytesconverter(b):s = b.decode(encoding)return strconverter(s)return bytesconverterdef graph_data(stock):fig = plt.figure()ax1 = plt.subplot2grid((1,1), (0,0))stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1m/csv'source_code = urllib.request.urlopen(stock_price_url).read().decode()stock_data = []split_source = source_code.split('\n')for line in split_source:split_line = line.split(',')if len(split_line) == 6:if 'values' not in line and 'labels' not in line:stock_data.append(line)date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,delimiter=',',unpack=True,converters={0: bytespdate2num('%Y%m%d')})x = 0y = len(date)ohlc = []while x < y:append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]ohlc.append(append_me)x+=1candlestick_ohlc(ax1, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')for label in ax1.xaxis.get_ticklabels():label.set_rotation(45)ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))ax1.grid(True)bbox_props = dict(boxstyle='round',fc='w', ec='k',lw=1)ax1.annotate(str(closep[-1]), (date[-1], closep[-1]),xytext = (date[-1]+3, closep[-1]), bbox=bbox_props)## # Annotation example with arrow## ax1.annotate('Bad News!',(date[11],highp[11]),## xytext=(0.8, 0.9), textcoords='axes fraction',## arrowprops = dict(facecolor='grey',color='grey'))###### # Font dict example## font_dict = {'family':'serif',## 'color':'darkred',## 'size':15}## # Hard coded text## ax1.text(date[10], closep[1],'Text Example', fontdict=font_dict)plt.xlabel('Date')plt.ylabel('Price')plt.title(stock)#plt.legend()plt.subplots_adjust(left=0.11, bottom=0.24, right=0.87, top=0.90, wspace=0.2, hspace=0)plt.show()graph_data('EBAY')
结果为:

