I am trying to learn Python. I am using the following program, which creates the image OK, but I want to save it. I tried some instructions I found on this site, but am getting the error message at the bottom. Any help would be appreciated.
Program:
import sys
import random
import matplotlib as plt
from graphics import *
def main():
m=1
n=2
offset=50
win = GraphWin("MyWin",500, 500)
win.setBackground(color_rgb(0,0,0))
for i in range(1,1000,1):
r= random.uniform(0,1)
q= int(3*r)
m = (m/2) + q*(q-1)*75
n = (n/2) + q*(3-q)*75
pt = Point(m + offset,n + offset)
pt.setOutline(color_rgb(255,255,0))
pt.draw(win)
print("graphic done")
plt.savefig("figure.png")
win.getMouse()
win.close()
if __name__ == '__main__':
main()
Error Message:
graphic done
Traceback (most recent call last):
File "fractal_1.py", line 29, in <module>
main()
File "fractal_1.py", line 24, in main
plt.savefig("figure.png")
AttributeError: module 'matplotlib' has no attribute 'savefig'
The call to plt.savefig("figure.png") will only work if you have imported as follows:
import matplotlib.pyplot as plt.
I believe your error lies with plt and what it actually references. If you imported like this:import matplotlib as plt
then you would need to call the required function like this: plt.pyplot.savefig("figure.png")
If you imported like this:import matplotlib.pyplot as plt
then you can call the required function like this: plt.savefig("figure.png")
Thanks for including the error, but what that's saying is that matplotlib doesn't have a savefig() function.
I think it's matplotlib.pyplot.savefig() as per this link: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.savefig.html
Edit your code to say: plt.pyplot.savefig().
Related
When I run the code:
import sys
import math
import numpy as np
import matplotlib.pyplot as plt
from typing import List, Tuple
import os
import scipy.io, scipy.signal
import colorednoise as cn
def generate_pink_noise(singal_length):
beta = 1
samples = singal_length
noise = cn.powerlaw_psd_gaussian(beta, samples)
return noise
I get:
Traceback (most recent call last):
File "...MEA_foward_model.py", line 11, in <module>
import colorednoise as cn
ModuleNotFoundError: No module named 'colorednoise'
Note the 'test' environment I'm using shown here when I get the error: environment.
However the same code runs without error in Jupiter notebook:
import colorednoise as cn
signal_length =10
beta = 1 # the exponent: 0=white noite; 1=pink noise; 2=red noise (also "brownian noise")
samples = signal_length # number of samples to generate (time series extension)
noise = cn.powerlaw_psd_gaussian(beta, samples)
This image shows (see top right corner) shows that the same environment is used
jupyter notebook output. What is causing this dissonance between the two different behaviours?
just new to python, and I believe this is not a big deal but because I am a freshman.
Basically, this is a simple program plotting a FM signal in time domain. I write a module by myself.
def FreqMod (fc,fm,t_domain)
pi=py.pi
if fc>fm:
delta=fc-fm
else:
delta=fm-fc
return py.cos(2*pi*fc*t_domain+ (delta/fm)*py.sin(2*pi*fm*t_domain))
def AmpMod(fc,fm,t_domain):
pi=py.pi
return py.cos(2*pi*fc*t_domain)*py.cos(2*pi*fm*t_domain)
And import it in another program
import numpy as py
import mylib
import matplotlib.pyplot as plt
pi=py.pi
y=mylib.FreqMod(5,1000,t=py.arange(0,2*pi,pi/4000))
plt.plot(y)
The lib file is located as the same directory as the program. But I Got this later:
Traceback (most recent call last):
File "...(The directory)...", line 14, in <module>
y=mylib.FreqMod(5,1000,t=py.arange(0,2*pi,pi/4000))
AttributeError: module 'mylib' has no attribute 'FreqMod'
It seems like I didn't import the module successfully. I have compared it with examples in how to write and import a module, but yet can't figure out why. This really confuse me as a beginner in python.
I got an error message from Python:
Traceback (most recent call last):
File "stock_script.py", line 9, in <module>
from matplotlib.finance import candlestick
ImportError: cannot import name candlestick
Why?
Matplotlib code has been changed...
Go into the script and replace "candlestick" by "candlestick_ohlc"
So it should read:
from matplotlib.finance import candlestick_ohlc
candlestick_ohlc(ax1, ...
Not very nice changing the name and breaking existing code...
I have fixed this by changing the import like this.
from matplotlib.finance import candlestick_ohlc as candlestick
No further changes are then needed in the code.
You need to add an underscore to it to use this same library:
from matplotlib.finance import _candlestick
I have some code that I wrote and imported to a new computer, I tried to do easy_install on astropysics and networkx but it seems that my previous (working) code has trouble with the easy_install version of astropysics. I've not seen this one before so I thought maybe someone here would have an idea. My relevant code is:
import os, sys
import numpy as np
import matplotlib.pyplot as plt
import asciitable
from scipy import stats
import astropysics
import astropysics.obstools
import astropysics.coords
import math
import pylab as P
import random
from random import randint
from pylab import *
from astropysics.coords import ICRSCoordinates,GalacticCoordinates
from scipy.optimize import curve_fit
f=open(sys.argv[1])
y= asciitable.read(f,Reader=asciitable.CommentedHeader,delimiter=' ')
f.close()
vhc = y['Vhelavg']
verr = y['Verravg']
Radeg=y['Radeg']
Decdeg=y['Decdeg']
Rcoeff=y['Rcoeffavg']
logg=y['loggavg']
vhcgood= (vhc != -99.9) & (vhc >= -400) & (vhc <= 400) & (logg<=2.3)
vhcg=vhc[vhcgood]
l=[]
b=[]
Radg=Radeg[vhcgood]
Decdg=Decdeg[vhcgood]
for i in xrange(len(Radg)):
gcoords=ICRSCoordinates(Radg[i],Decdg[i]).convert(GalacticCoordinates)
l.append(gcoords.l.radians)
b.append(gcoords.b.radians)
The Error is:
Traceback (most recent call last):
File "gauss01_15.py", line 46, in <module>
gcoords=ICRSCoordinates(Radg[i],Decdg[i]).convert(GalacticCoordinates)
File "/Library/Python/2.7/site-packages/Astropysics-1.0-py2.7.egg/astropysics/coords/coordsys.py", line 1895, in convert
res = EpochalLatLongCoordinates.convert(self,tosys,optimize)
File "/Library/Python/2.7/site-packages/Astropysics-1.0-py2.7.egg/astropysics/coords/coordsys.py", line 1781, in convert
res = LatLongCoordinates.convert(self,tosys,optimize)
File "/Library/Python/2.7/site-packages/Astropysics-1.0-py2.7.egg/astropysics/coords/coordsys.py", line 1728, in convert
return CoordinateSystem.convert(self,tosys)
File "/Library/Python/2.7/site-packages/Astropysics-1.0-py2.7.egg/astropysics/coords/coordsys.py", line 1098, in convert
convpath = CoordinateSystem.getTransformPath(self.__class__,tosys)
File "/Library/Python/2.7/site-packages/Astropysics-1.0-py2.7.egg/astropysics/coords/coordsys.py", line 1038, in getTransformPath
path = nx.shortest_path(g,fromsys,tosys,weighted=True)
TypeError: shortest_path() got an unexpected keyword argument 'weighted'
I've never gotten this before and never had any issues with the simple python coordinate transform in astropysics. Any ideas are appreciated.
You probably need to upgrade your astropysics version. There was a change in the networkx (nx) dependency of astropysics, that has been taken care of in more recent version of astropysics. (The keyword argument weighted changed to weight, and apparently you have incompatible versions of astropysics and networkx to handle this change.)
The relevant fix is show in these lines in astropysics.
You probably want to upgrade the networkx package as well, if that doesn't happen automatically for you.
easy_install --upgrade astropysics
easy_install --upgrade networkx
hopefully does it for you.
I am trying to use the class shown here to interpolate some data.
I am having trouble getting this class to work. A minimal example is:
#!/usr/bin/env python
import sys
from mayavi.mlab import *
from mayavi import mlab
from numpy import *
import numpy as np
from mayavi.scripts import mayavi2
from mayavi.sources.vtk_file_reader import VTKFileReader
from mayavi.modules.outline import Outline
from mayavi.modules.grid_plane import GridPlane
from mayavi.modules.contour_grid_plane import ContourGridPlane
from mayavi.modules.iso_surface import IsoSurface
from mayavi.modules.scalar_cut_plane import ScalarCutPlane
import scipy
from scipy import interpolate
from scipy.interpolate import griddata
#from scipy.interpolate import RegularGridInterpolator
print 'Argument List:', str(sys.argv)
if (len(sys.argv)==5):
NX = int(sys.argv[1])
NY = int(sys.argv[2])
NZ = int(sys.argv[3])
fname = sys.argv[4]
else:
print "Error in parsing the command line arguments"
print "Command line arguments are: N_X N_Y N_Z filename "
sys.exit()
clf()
figure(bgcolor=(1, 1, 1))
len(sys.argv)
data = genfromtxt(fname)
x,y,z = mgrid[ 0:NX:1, 0:NY:1, 0:NZ:1 ]
#print(x)
index = 0
V=0*x
for k in range(NZ):
for j in range(NY):
for i in range(NX):
V[i][j][k] = 1000*data[index,5]
scipy.interpolate.RegularGridInterpolator(V, V, method='linear', bounds_error=True, fill_value=nan) #ERROR
The only bits really of interest to my current problem are the last line and all the import commands at the beginning
My error is:
Traceback (most recent call last):
File "contour-3d.py", line 70, in <module>
scipy.interpolate.RegularGridInterpolator(W, W, method='linear', bounds_error=True, fill_value=nan)
AttributeError: 'module' object has no attribute 'RegularGridInterpolator'
I'm not too familiar with python, so this may be a very basic error.
From the docs:
New in version 0.14.
It's likely you have a previous version of SciPy. If you are using Ubuntu, try running pip:
pip install --user --upgrade scipy
You might need some additional dependencies:
sudo apt-get install gcc gfortran python-dev libblas-dev liblapack-dev cython
For more information see http://www.scipy.org/install.html and http://www.scipy.org/scipylib/building/
scipy.interpolate.RegularGridInterpolator is a new function in scipy 0.14.x. You are likely to be using a older version. Updating scipy should solve the problem.