2016-05-29 58 views
0

我用於繪製MovingAverages的聲明ax1.plot(xLength[-SP:], Av1[-SP:], '#fa32e3', linewidth=1.5)正在導致我的y軸刻度超出繪圖窗口的末端。因此,我無法通過使用prune擺脫top tick標籤來消除y軸上端的混亂。matplotlib:爲什麼我的Y軸扭曲?

如果您評論ax1.plot(xLength[-SP:], Av1[-SP:], '#fa32e3', linewidth=1.5) out,y軸刻度顯示正確,允許我修剪頂部刻度標籤(top tick label = 5.0)。

什麼導致了奇怪的Y軸刻度行爲?如何在繪製MovingAverages時正確顯示我的y軸刻度,所以我可能會在最上面的y軸刻度標記'4.8'?

我的圖表未繪製MovingAverages顯示正確的y軸預剪切: enter image description here 繪製MovingAverages之後的圖表。請注意如何y軸發生了偏移(並且不再修剪,能): enter image description here

這裏是一個砍下代碼版本:

# Visualize my stock data 

import numpy as np 
import time 
import datetime 
import matplotlib.pyplot as plt 
import matplotlib.ticker as mticker 
import matplotlib.dates as mdates 
from 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 the x-axis used for plotting coordinates (xLength, y) 
     SP = len(date[MA2-1:])    # Right hand stopping point so MAs align with CandleStix 
     candleAr = list(zip(xLength,openp,closep,highp,lowp,volume)) # The data set 



     # Formatter Class to 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): 
       # This gets called even when out of bounds, so IndexError must be 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') 


# The 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, and the like 
     ax1.grid(True, color='w') 
     ax1.yaxis.label.set_color('w') 

     # My 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) 

################################################################## 
########## This is causing the problem with the 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 as e: 
     print('failed main loop',str(e)) 

for stock in eachStock: 
    graphData(stock, 13, 50) # These numbers correspond to the Moving Average lengths 

和數據集「AMD.txt」可用在這裏:http://pastebin.com/CJm7n3y1

+1

您確定您使用正確的軸嗎? 'plt.gca()。yaxis.set_major_locator(mticker.MaxNLocator(prune ='upper'))'可能抓錯了一個? – tacaswell

+0

我相當肯定我正在使用正確的y軸。如果我將'plt.gca()。yaxis.set_major_locator(mticker.MaxNLocator(prune ='upper'))'的修剪值更改爲'prune ='lower''或'prune ='both'',則較低的Stock 1.6價格剔除,但從來沒有上限。 – Jack

+0

你能用一個可複製的例子重現這個嗎?允許定位器將邊界位置返回,這可能是修剪邏輯中的一個錯誤。我也對'get_ylim()'返回的內容感到困惑,你說它是[1.5,5.0],但是頂部/底部的刻度在[1.6,4.8]。 – tacaswell

回答

0

我不得不設置軸限制和蜱/刻度標記明確使用 plt.axis([xLength[0], xLength[-1], ax1.get_ylim()[0], ax1.get_ylim()[1]]) 然後修剪產生的軸與 plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))

現在我的圖表正在顯示正確的座標軸刻度/刻度標籤,並且我能夠以所需的值爲prune