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.
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()
Related
I am trying to display a plot with matplotlib and django following this and this questions, however it seems not working, I tried both solutions and only while using IO i get an empty canvas, but when I try to plot a 'real' plot I get the error in the title.
This is my view:
import django
from matplotlib.backends.backend_agg import FigureCanvasAgg as
FigureCanvas
from matplotlib.figure import Figure
import numpy as np
import matplotlib.pyplot as plt
import io
def mplimage(request):
fig = Figure()
canvas = FigureCanvas(fig)
x = np.arange(-2, 1.5, .01)
y = np.sin(np.exp(2 * x))
plt.plot(x, y)
buf = io.BytesIO()
plt.savefig(buf, format='png')
plt.close(fig)
response = django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
and here the link in urls.py:
import mpl.views
url(r'mplimage.png', mpl.views.mplimage)
This works if you save the file objects as JPEG (requires PIL) instead of PNG using print_jpg() method instead of print_png().
Change:
response = django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
To:
response = HttpResponse(content_type='image/jpg')
canvas.print_jpg(response)
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np
import django
def showimage(request):
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
x = np.arange(-2,1.5,.01)
y = np.sin(np.exp(2*x))
ax.plot(x, y)
response = HttpResponse(content_type='image/jpg')
canvas.print_jpg(response)
return response
from pylab import *
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib.collections import LineCollection
from mpl_toolkits.basemap import Basemap,cm
import shapefile
import dbflib
import dbflib
Traceback (most recent call last):
File "<ipython-input-398-b5a771049653>", line 1, in <module>
import dbflib
ModuleNotFoundError: No module named 'dbflib'
Tried solutions suggested by other posts like install/uninstall tookit, doesn't work. Anyone has this kind issue?
I use Embedding Python in C++, in my program, I have to run the python module many times. Unfortunately, the plt.show() only gets the figure one time, the others get the null figure
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Circle
import time
def show(x,y,x1,y1):
fig=plt.figure()
fig.gca().invert_yaxis()
ax1 = fig.add_subplot(111)
cir1 = Circle(xy = (x1, y1), radius=0.02, alpha=0.5)
ax1.add_patch(cir1)
print len(x)
print x1
ax1.set_title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
ax1.scatter(x,y,c = 'r',marker = 'o')
plt.ion()
plt.show()
time.sleep(1)
plt.close()
return 'ok'
I am trying to plot a function F(x1,x2) in 3D matplotlib, follwoing a tutorial from here:
http://glowingpython.blogspot.com/2012/01/how-to-plot-two-variable-functions-with.html
Once I try to run the code, the figure turns out to be empty, not even the axes output is seen. I was wondering if anyone could figure out the resaon behind this behavior. I am using python 2.7
from __future__ import division
from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
import math
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
from matplotlib import pylab
from numpy import arange,array,ones
from scipy import stats
import numpy
import matplotlib.ticker as mtick
import sys
import os
# the function that I'm going to plot
def z_func(x1,x2):
return exp(-(1-x1)**2 - 100*((x2-x1**2)**2))
x1 = arange(5.0,-5.0,-0.01)
x2 = arange(-5.0,5.0,0.01)
X1,X2 = meshgrid(x1, x2) # grid of point
Z = z_func(X1, X2) # evaluation of the function on the grid
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X1, X2, Z, rstride=1, cstride=1, cmap=cm.RdBu,linewidth=0, antialiased=False)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_zlabel('z-axis')
ax.view_init(elev=25, azim=-120)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
Your code works for me. I just needed to wait till the computer will finish the computation. The long computation is because of the size of x1 and x2. Try to change these lines:
x1 = arange(5.0,-5.0,-0.01)
x2 = arange(-5.0,5.0,0.01)
to the following lines:
x1 = arange(5.0,-5.0,-0.1)
x2 = arange(-5.0,5.0,0.1)
p.s. I advise you to arrange your imports. You only need the following:
from numpy import exp, arange
import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from pylab import meshgrid
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
I have Python 2.7 Win 32 and have installed Matplotlib, Numpy, PyParsing, Dateutil. In IDLE I place in the 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,bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')
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()
there are three variable but only two values given
date,bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')
you probably need to change that line to :
date=mdates.strpdate2num('%Y%m%d%H%M%S')
bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')