2016-03-22 133 views
-1

儘管嘗試了各種matplotlib方法,但似乎無法弄清楚如何讓我的y軸標籤位於右側,其中包括:無法在圖表的右側獲得y軸標籤

  • ohlc_axis.yaxis.tick_right()
  • ohlc_axis.tick_params(軸= 'Y',顏色= 'K',labelleft = '關閉', labelright = '上')
  • ohlc_axis。 yaxis.set_ticks_position('right')
  • ohlc_axis.yaxis.set_label_position('right')

我的腳本全文如下。無法弄清楚我在這裏錯過了什麼。

import matplotlib 
import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 
import matplotlib.ticker as mticker 
from matplotlib.finance import plot_day_summary 
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MonthLocator, MONDAY 
import indicators 
import datetime 
from datetime import timedelta 

matplotlib.rcParams.update({'font.size': 9}) 

import numpy as np 
import urllib2 
import datetime as dt 

# Setup charting 
mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays 
alldays = DayLocator()    # minor ticks on the days 
firstDay = DayLocator(1) 
weekFormatter = DateFormatter('%b %d') # Eg, Jan 12 
dayFormatter = DateFormatter('%d')  # Eg, 12 
monthFormatter = DateFormatter('%b %y') 

# every Nth month 
months = MonthLocator(range(1,13), bymonthday=1, interval=1) 

def bytespdate2num(fmt, encoding='utf-8'): 
    strconverter = mdates.strpdate2num(fmt) 
    def bytesconverter(b): 
     s = b.decode(encoding) 
     return strconverter(s) 
    return bytesconverter 


def graph_data(stock, MA1, MA2): 
    ################Get the stock data from yahoo################ 
    stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=2y/csv' 

    source_code = urllib2.urlopen(stock_price_url).read().decode() 
    #print 'source_code: ', source_code 
    stock_data = [] 
    split_source = source_code.split('\n') 
    #Loop through each row of csv and add to the stock_data array 
    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')}) 

    #Add values to ohlc array 
    x = 0 
    y = len(date) 
    ohlc = [] 

    while x < y: 
     append_me = date[x], openp[x], closep[x], highp[x], lowp[x], volume[x] 
     ohlc.append(append_me) 
     x+=1 
    ################END OF DATA MANIPULATION################ 

    Av1 = indicators.movingaverage(closep, MA1) 
    Av2 = indicators.movingaverage(closep, MA2) 

    SP = len(date[MA2-1:]) 

    fig = plt.figure() 

    ohlc_axis = plt.subplot2grid((1,1), (0,0)) 

    #Draw OHLC 
    plot_day_summary(ohlc_axis, ohlc, ticksize=2, colorup='k', colordown='k') 
    Label1 = str(MA1)+' SMA' 
    Label2 = str(MA2)+' SMA' 

    ohlc_axis.grid(True, color='black', which='minor') 
    ohlc_axis.xaxis.set_major_formatter(mdates.DateFormatter('%b')) 
    ohlc_axis.xaxis.set_minor_locator(mondays) 
    ohlc_axis.xaxis.set_major_locator(mticker.MaxNLocator(15)) 
    ohlc_axis.xaxis.set_major_formatter(mdates.DateFormatter('%b')) 
    ohlc_axis.yaxis.set_major_locator(mticker.MaxNLocator(8)) 
    ohlc_axis.yaxis.set_minor_locator(mticker.MaxNLocator(40)) 
    #ohlc_axis.tick_params(axis='y', colors='k', labelleft='off', labelright='on') 
    ohlc_axis.yaxis.set_ticks_position('right') 
    ohlc_axis.yaxis.set_label_position('right') 
    #Draw MA1 and MA2 

    ohlc_axis.plot(date[-SP:],Av1[-SP:],'black', linewidth=1.5, linestyle='dashed') 
    ohlc_axis.plot(date[-SP:],Av2[-SP:],'black', linewidth=1.5, linestyle='dotted') 

    #draw RSI 
    rsi = indicators.rsiFunc(closep) 
    rsiCol = 'black' 
    rsi_axis = ohlc_axis.twinx() 
    rsi_axis.set_ylim(0, 4*rsi.max()) 
    rsi_axis.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=.5) 
    rsi_axis.axes.yaxis.set_ticklabels([]) 

    #draw Volume bar chart 
    volume_axis = ohlc_axis.twinx() 
    volume_axis.bar(date[-SP:], volume[-SP:], color="k", width=.5, align='center') 
    volume_axis.axes.yaxis.set_ticklabels([]) 
    volume_axis.set_ylim(0, 5*volume.max()) 
    volume_axis.tick_params(axis='y', colors='b', labelleft='off', labelright='on') 

    plt.xlim([datetime.date.today() - timedelta(days=365), datetime.date.today() + timedelta(days=30)]) 

    plt.show() 
    fig.savefig('chart.png', facecolor=fig.get_facecolor()) 


graph_data('BAC', 50, 150) 

我在上面引用了一個叫做指標的腳本。指標.py如下:

import numpy as np 
import matplotlib 
import pylab 

def rsiFunc(prices, n=14): 
    deltas = np.diff(prices) 
    seed = deltas[:n+1] 
    up = seed[seed>=0].sum()/n 
    down = -seed[seed<0].sum()/n 
    rs = up/down 
    rsi = np.zeros_like(prices) 
    rsi[:n] = 100. - 100./(1.+rs) 

    for i in range(n, len(prices)): 
     delta = deltas[i-1] # cause the diff is 1 shorter 

     if delta>0: 
      upval = delta 
      downval = 0. 
     else: 
      upval = 0. 
      downval = -delta 

     up = (up*(n-1) + upval)/n 
     down = (down*(n-1) + downval)/n 

     rs = up/down 
     rsi[i] = 100. - 100./(1.+rs) 

    return rsi 

def movingaverage(values, window): 
    weigths = np.repeat(1.0, window)/window 
    smas = np.convolve(values, weigths, 'valid') 
    return smas # as a numpy array 

def ExpMovingAverage(values, window): 
    weights = np.exp(np.linspace(-1., 0., window)) 
    weights /= weights.sum() 
    a = np.convolve(values, weights, mode='full')[:len(values)] 
    a[:window] = a[window] 
    return a 


def computeMACD(x, slow=26, fast=12): 
    """ 
    compute the MACD (Moving Average Convergence/Divergence) using a  fast and slow exponential moving avg' 
    return value is emaslow, emafast, macd which are len(x) arrays 
    """ 
    emaslow = ExpMovingAverage(x, slow) 
    emafast = ExpMovingAverage(x, fast) 
    return emaslow, emafast, emafast - emaslow 

這是我現在看到的圖表。我希望將y軸價格標籤移到右側。

enter image description here

+0

代碼不會在當前版本的matplotlib中運行。哪些「指標」包是這個?無論如何,如果你延遲設置標籤位置,直到調用show之前會發生什麼? (順便說一句,把它放在你的函數中是非常難看的... fwiw。) – Alan

+0

這不是一個最小的工作示例,如果沒有在財務模塊上發生縮進錯誤和導入錯誤,我無法運行該工具。請提供一個較小的工作代碼,表明我們可以工作的相同問題。 – nluigi

+0

新增指標.py。 –

回答

0

你的第一次嘗試似乎做工精細用一個簡單的情節:

import matplotlib.pyplot as plt 
fig, ax = plt.subplots() 
p = [n for n in xrange(5)] 
ax.plot(p, p) 
ax.yaxis.tick_right() 
plt.draw() 

enter image description here

或者該作品,以及與多種數據:

import matplotlib.pyplot as plt 
fig, ax1 = plt.subplots() 
p1 = [n for n in xrange(5)] 
p2 = [i**2 for i in p1] 
ax1.plot(p1, p1, 'o') 
ax2 = ax1.twinx() 
ax2.plot(p1, p2) 
plt.draw() 

enter image description here

不能運行你的腳本,很難說爲什麼你的y軸不會切換到正確的。

+0

我在上面的問題中包含了indicators.py。 –