Question

I have Python 2.7 Win 32 and have installed Matplotlib, Numpy, PyParsing, Dateutil. In IDLE I place in the following code:

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np

def graphRawFX () :
    date=mdates.strpdate2num('%Y%m%d%H%M%S')
    bid, ask = np.loadtxt('GPBUSD1d.txt', unpack=True)
    delimiter=',',
    converters={0:mdates.strpdate2num('%Y%m%d%H%M%S') }
    fig = plt.figure(figsize=(10,7))
    ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)

    ax1.plot(date,bid)
    ax1.plot(date,ask)

ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))

plt.grid(True)
plt.show()

Running the code results in to the following:

Traceback (most recent call last):
  File "C:/Users/Emanuel/Desktop/test.py", line 18, in <module>
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
NameError: name 'ax1' is not defined

Any suggestion to editing the code would be helpful.

Était-ce utile?

La solution

This is because you are calling ax1 outside the method in which it has been defined it. Perhaps you should include that line in the method as well.

or else:

You can create the ax1 object outside the method and then change some of its attributes as necessary in your function by using global ax1

EDIT: It should look something like this:

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np


ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)

def graphRawFX (axes1) :

    date=mdates.strpdate2num('%Y%m%d%H%M%S')
    bid, ask = np.loadtxt('GPBUSD1d.txt', unpack=True)
    delimiter=',',
    converters={0:mdates.strpdate2num('%Y%m%d%H%M%S') }
    fig = plt.figure(figsize=(10,7))

    axes1.plot(date,bid)
    axes1.plot(date,ask)

graphRawFX(ax1)

ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))

plt.grid(True)
plt.show()
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top