尽管尝试了各种matplotlib方法,但我似乎无法弄清楚如何让我的y轴标签位于右侧,包括:
我的脚本完整地在下面。无法弄清楚我在这里失踪了什么。
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)
我在上面引用了一个名为指标的脚本。 indicators.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轴价格标签移到右侧。
答案 0 :(得分: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()
或者,这也适用于多个数据:
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()
无法运行脚本,很难说为什么你的y轴不会切换到右边。