我用来绘制MovingAverages ax1.plot(xLength[-SP:], Av1[-SP:], '#fa32e3', linewidth=1.5)
的语句导致我的y轴刻度超出了绘图窗口的末尾。因此,我无法通过使用prune
来消除顶部刻度标签来消除y轴上端的混乱。
如果您评论ax1.plot(xLength[-SP:], Av1[-SP:], '#fa32e3', linewidth=1.5)
,则y轴标记正确显示,允许我修剪顶部刻度标签(顶部刻度标签= 5.0)。
导致奇怪的y轴嘀嗒行为的原因是什么?如何在绘制MovingAverages时正确显示我的y轴刻度,所以我可以prune
最上面的y轴刻度标签' 4.8'?
我的图表没有绘制MovingAverages显示正确的y轴pre-prune: 绘制MovingAverages后的我的图表。注意y轴如何移位(并且不再可修剪):
这是一个简化的代码版本:
# 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
和数据集&#39; AMD.txt&#39;可在此处获取:http://pastebin.com/CJm7n3y1
答案 0 :(得分: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
所需的值。