python - matplotlib: Why is my Y-Axis distorting? -
the statement use plot movingaverages, ax1.plot(xlength[-sp:], av1[-sp:], '#fa32e3', linewidth=1.5), causing y-axis ticks go beyond end of plot window. result, unable eliminate clutter @ upper end of y-axis using prune rid of top tick label.
if comment ax1.plot(xlength[-sp:], av1[-sp:], '#fa32e3', linewidth=1.5) out, y-axis ticks display correctly allowing me prune top tick label (top tick label = 5.0).
what causing strange y-axis tick behavior? how can display y-axis ticks when plotting movingaverages, may prune uppermost y-axis tick label '4.8'?
my chart without plotting movingaverages displaying correct y-axis pre-prune:
chart after plotting movingaverages. notice how y-axis has shifted (and no longer prune-able): 
here chopped down code version:
# visualize stock data import numpy np import time import datetime import matplotlib.pyplot plt import matplotlib.ticker mticker import matplotlib.dates mdates matplotlib.finance import _candlestick import matplotlib import pylab matplotlib.rcparams.update({'font.size': 9}) eachstock = ['amd'] def movingaverage(values, window): weights = np.repeat(1.0, window)/window smas = np.convolve(values, weights, 'valid') return smas def graphdata(stock, ma1, ma2): try: stockfile = 'amd.txt' date, closep, highp, lowp, openp, volume = np.loadtxt(stockfile, delimiter=',',unpack=true, converters={ 0: mdates.bytespdate2num('%y%m%d')}) xlength = range(len(date)) # length of x-axis used plotting coordinates (xlength, y) sp = len(date[ma2-1:]) # right hand stopping point mas align candlestix candlear = list(zip(xlength,openp,closep,highp,lowp,volume)) # data set # formatter class eliminate weekend data gaps on chart class jackarow(mdates.dateformatter): def __init__(self, fmt): mdates.dateformatter.__init__(self, fmt) def __call__(self, x, pos=0): # gets called when out of bounds, indexerror must prevented. if x < 0: x = 0 elif x >= len(date): x = -1 return mdates.dateformatter.__call__(self, date[int(x)], pos) fig = plt.figure(facecolor='#07000d') # candlestick plot ax1 = plt.subplot2grid((6, 4), (1,0), rowspan=4, colspan=4, axisbg='#07000d') _candlestick(ax1, candlear[-sp:], width=.75, colorup='#53c156', colordown='#ff1717') # format colors, axis, , ax1.grid(true, color='w') ax1.yaxis.label.set_color('w') # broken pruner plt.gca().yaxis.set_major_locator(mticker.maxnlocator(prune='upper')) ax1.xaxis.set_major_locator(mticker.maxnlocator(10)) ax1.xaxis.set_major_formatter(jackarow('%y-%m-%d')) ax1.spines['bottom'].set_color("#5998ff") ax1.spines['top'].set_color("#5998ff") ax1.spines['left'].set_color("#5998ff") ax1.spines['right'].set_color("#5998ff") ax1.tick_params(axis='y', colors='w') ax1.tick_params(axis='x', colors='w') plt.ylabel('stock price') # plot moving averages av1 = movingaverage(closep, ma1) ################################################################## ########## causing problem prune ########### ax1.plot(xlength[-sp:], av1[-sp:], '#fa32e3', linewidth=1.5) ################################################################## ################################################################## plt.suptitle(stock, color='w') plt.setp(ax1.get_xticklabels(), visible=false) plt.subplots_adjust(left=.10, bottom=.14, right=.93, top=.95, wspace=.20, hspace=0) plt.show() fig.savefig('savedchart.png', facecolor=fig.get_facecolor()) except exception e: print('failed main loop',str(e)) stock in eachstock: graphdata(stock, 13, 50) # these numbers correspond moving average lengths and data set 'amd.txt' available here: http://pastebin.com/cjm7n3y1
i had set axis limits , ticks/tick labels explicitly using plt.axis([xlength[0], xlength[-1], ax1.get_ylim()[0], ax1.get_ylim()[1]]) , prune resulting axis plt.gca().yaxis.set_major_locator(mticker.maxnlocator(prune='upper'))
now chart displaying correct axis ticks/tick labels, , able prune desired values.
Comments
Post a Comment