【问题标题】:Can't get y-axis labels onto the right side of the chart无法将 y 轴标签放在图表的右侧
【发布时间】:2016-03-22 01:37:03
【问题描述】:

尽管尝试了各种 matplotlib 方法,但我似乎无法弄清楚如何将我的 y 轴标签定位到右侧,包括:

  • ohlc_axis.yaxis.tick_right()
  • 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')

我的脚本全文如下。无法弄清楚我在这里缺少什么。

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 轴价格标签移到右侧。

【问题讨论】:

  • 当前版本的matplotlib 无法运行代码。这是哪个indicators 包?无论如何,如果您在调用show 之前延迟设置标签位置会发生什么? (顺便说一句,把它放在你的函数中是相当丑陋的...... fwiw。)
  • 这不是一个最小的工作示例,如果在财务模块上出现缩进错误和导入错误,我无法运行它。请提供一个较小的工作代码,它显示出我们可以解决的相同问题。
  • 添加了indicators.py.
  • @Alan,将 ohlc_axis.yaxis.tick_right() 移动到 plt.show() 的正上方,谢谢。

标签: python matplotlib charts


【解决方案1】:

您的第一次尝试似乎适用于简单的情节:

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 轴不会向右切换。

【讨论】:

  • 我在上面的问题中包含了indicators.py。
猜你喜欢
  • 2023-03-30
  • 2020-05-11
  • 2023-01-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多