I am trying to embed a stock price chart in a Tkinter canvas widget. I have a fully functional stock price graph written in matplotlib. While trying to embed my graph in Tkinter I have discovered (been informed) that a matplotlib graph that is written as a plot can not be properly embeded in Tkinter and that the graph must be in the form of a figure for the embedding to properly work. For illustration purposes here is a matplotlib sample graph in the form of a plot.
def schart20(stock_sym):
x = [1,2,3,4]
y = [20,21,20.5, 20.8]
plt.plot(x,y)
plt.show()
Here is the same graph but in the form of a figure.
def schart21(stock_sym):
x = [1,2,3,4]
y = [20,21,20.5, 20.8]
fig = Figure()
axes = fig.add_subplot(111)
axes.plot(x,y)
return fig
The schart21 code can be sucessfully embedded in Tkinter but the schart20 code cannot. My stock price graph code is in the form of a plot and I need to convert it to the form of a figure. I have very little experience with matplotlib and am not sure how to modify my code as required. Here is my stock price chart code. This code is fully functional but requires access to an underlying file to work.
def graphData(stock, MA1, MA2):
try:
stockFile = '/Users/BioASys/BioasysDB/CompanyStockPriceData/'+stock+'.txt'
date, closep, highp, lowp, openp,volume=np.loadtxt(stockFile,delimiter=',',unpack=True,
converters={ 0: mdates.strpdate2num('%Y%m%d')})
x = 0
y = len(date)
candleAr = []
while x < y:
appendLine = date[x], openp[x], closep[x], highp[x], lowp[x], volume[x]
candleAr.append(appendLine)
x+=1
Av1 = movingaverage(closep, MA1)
Av2 = movingaverage(closep, MA2)
SP = len(date[MA2-1:])
label1 = str(MA1) + ' SMA'
label2 = str(MA2) + ' SMA'
fig = plt.figure()
ax1 = plt.subplot2grid((5,4),(0,0), rowspan=4, colspan=4)
candlestick(ax1, candleAr[-SP:], width=0.6, colorup='g', colordown='r')
ax1.plot(date[-SP:],Av1[-SP:],'#5998ff', label=label1, linewidth=1.5)
ax1.plot(date[-SP:],Av2[-SP:],'blue', label=label2, linewidth=1.5)
plt.ylabel('Stock price')
ax1.grid(True)
plt.legend(loc=3,prop={'size':7},fancybox=True,)
ax2 = plt.subplot2grid((5,4), (4,0), sharex=ax1, rowspan=1, colspan=4)
#ax2 = plt.subplot2grid((5,4), (4,0), rowspan=1, colspan=4)
ax2.bar(date, volume)
ax2.axes.yaxis.set_ticklabels([])
plt.ylabel('Volume')
ax2.grid(True)
ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
for label in ax1.xaxis.get_ticklabels():
label.set_rotation(90)
for label in ax2.xaxis.get_ticklabels():
label.set_rotation(45)
plt.xlabel('Date')
#plt.ylabel('Stock Price')
plt.suptitle(stock+' Stock Price')
plt.setp(ax1.get_xticklabels(), visible=False)
plt.subplots_adjust(left=.09, bottom=.18, right=.94, top=.94, wspace=.20, hspace=0)
plt.show()
#fig.savefig('example.png') # saves a copy of the sticok chart to example.png
except Exception, e:
print 'failed main loop',str(e)
If anybody knows how to convert this from a plot to a figure I would appreciate the help. Sincerely, George