matplotlib:为什么我的YAxis扭曲了?

2024-06-23 19:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我用来绘制移动平均值的语句ax1.plot(xLength[-SP:], Av1[-SP:], '#fa32e3', linewidth=1.5),导致y轴刻度超出绘图窗口的末尾。因此,我无法通过使用prune来消除y轴上端的混乱,从而消除顶部的勾号标签。在

如果您将ax1.plot(xLength[-SP:], Av1[-SP:], '#fa32e3', linewidth=1.5)注释掉,y轴记号将正确显示,允许我修剪顶部记号标签(top tick label=5.0)。在

是什么导致了奇怪的y轴滴答行为?如何在绘制移动平均值时正确显示y轴刻度,以便prune最上面的y轴刻度标签“4.8”?在

我的图表不绘制移动平均值显示正确的y轴预修剪: enter image description here 我的图表在绘制移动平均数之后。请注意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

以及数据集'修改.txt'在此处可用:http://pastebin.com/CJm7n3y1


Tags: theimportdateplotmatplotlibasstock绘制
1条回答
网友
1楼 · 发布于 2024-06-23 19:28:20

我必须使用 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所需的值。在

相关问题 更多 >

    热门问题