So there was this thread talking about why matplotlib does not show when executing
python myfile.py
The most popular answer was about resetting matplotlibrc file. What would need to be reset in this file?
Also, some suggest to include matplotlib.use('TkAgg') in the import. Below is my python file:
#myfile.py
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
def dyn_draw():
x = np.linspace(0, 6 * np.pi, 100)
y = np.sin(x)
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma
for phase in np.linspace(0, 10 * np.pi, 500):
line1.set_ydata(np.sin(x + phase))
fig.canvas.draw()
fig.canvas.flush_events()
if __name__ == "__main__":
dyn_draw()
Running that with python myfile.py, I get the following error:
ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running
Another thread here discussed this error. But the solution still does not work (i.e. restarting the kernel).
How to plot this particular python code with the python command?
You are trying to run matplotlib interatively in a non-interactive environment. The code compiles, but errors at run-time because you running a script.
Have you tried running this in Google Colab? The resource provides free (to a certain point) GPU usage and block coding for interactive visualizations.
Best of luck :)
Related
Just getting into programming by going through a load of beginner projects. I started one to plot sine and cosine curves, and the code they gave was:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 4*np.py, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
Every time I try and run the code, it gives the error:
Traceback (most recent call last):
File "C:/Users/Alex/PycharmProjects/projects2/sin2.py", line 5, in <module>
x = np.arange(0, 4*np.py, 0.1)
File "C:\Users\Alex\anaconda3\envs\projects2\lib\site-packages\numpy\__init__.py", line 220, in __getattr__
"{!r}".format(__name__, attr))
AttributeError: module 'numpy' has no attribute 'py'
I've reinstalled Python, pycharm, and numpy to no avail. I believe I'm properly using the anaconda interpreter and I see numpy is properly installed on it. I'm not sure what else I should try, so any suggestions would help. Maybe I should try another IDE? I do like Pycharm so far but I have seen other people with similar issues using Pycharm, so any suggestions there would also be welcome.
I think you are trying to get np.pi
The constant 3.1415926535897932384626433...
If you change it in your code:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 4 * np.pi, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
It properly runs
I not very familiar with numpy, but I looked through the docs and couldn't find anything for py being part of numpy. Maybe I didn't look hard enough, but it could have been replaced with an update? Also, you could try changing it to "np.py()" with parentheses because it could just be a function instead (however that is probably not likely assuming you got this from a prebuilt project).
I don't know, why are you using 4*np.py, I have seen the documentation of NumPy and it has no such attribute as py. You can try following:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.title('sine wave') # To give a title
plt.xlabel('Time') # To give a x-label
plt.ylabel('Y-values') # To give a y-label
plt.grid(True, which='both') # Turns Grid to True
plt.axhline(y=0, color='k') # Draw a black horizontal line at y=0
plt.show()
Output:
This code works on one machine, but not the other. I can't seem to isolate the issue with the dependencies.
Sample code from: https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/simple_plot.html
--
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
plt.show()
--> TypeError: Cannot read property 'props' of undefined
This code does not produce a stack trace of explicitly fail. The TypeError: is returned by the call to plt.show(). I tried searching for this error, but I couldn't find anything reported. (I added a screenshot of what visual-studio on the server I am working on shows. I will likely just create a docker of my other environment as I should have done that in the first place to avoid having my configuration break.) The graph saves correctly to file. It's just an issue with plt.show().
np.version
'1.17.2'
matplotlib.version
'3.1.1'
screen-shot
graph-saves-correctly
Can you tell us on which line it fails specifically? Which function call causes the issue? You could comment everything and then uncomment every line until an error occurs on execution. Maybe there's a github page of this issue.
My suspicion is, that it's the ax.set() call. Haven't seen that before and never used it. Maybe it's deprecated in mpl 3.1.1. Apparently, this error can occur, when you pass a parameter that the function doesn't know (xlabel,ylabel,title): Uncaught TypeError: Cannot read property 'value' of undefined
As a test, try running this:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set_ylabel('voltage (mV)')
ax.set_xlabel('time (s)')
ax.set_title('About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
plt.show()
Running following code inside python interpretor displays a figure with random values
>>>fig = plt.figure();ax1 = fig.add_subplot(111);plt.ion();ax1 = ax1.imshow(np.random.rand(256,256))
while running the following script as a file does not display any output/figure.
import numpy as np
import matplotlib.pyplot as plt
import time
fig = plt.figure()
ax1 = fig.add_subplot(111)
plt.ion()
ax1 =ax1.imshow(np.random.rand(256,256))
what is the reason for difference in behaviour?
I suspect what is going on is that
matplotlib.rcParams['interactive'] == True
and this is set in your .matplotlibrc file.
which means that plt.show is non-blocking (so that you get a figure that you can interact with and an command prompt you can type more code at). However, in the case of a script the (implicit) plt.show does not block so the script exits, taking the figure with it.
I suggest the setting the interactive rcparam to False and then either explitily setting it to true in the repl or (the preferred method) use IPython and the %matplotlib magic.
I have the next code in python
import np_plots as npp
import matplotlib.pyplot as plt
import numpy as np
import math as m
import scipy
from scipy.integrate import odeint
def plotLimitCycle(bval):
rhs = lambda X, t: [-X[0]+X[1]*X[0]**2, bval - X[1]*X[0]**2]
xeq, yeq = bval, 1.0/bval
cyclerad = m.sqrt(1-bval)
nbh = min(cyclerad, 0.05)
IC = [xeq-nbh/5.0, yeq-nbh/5.0]
time_span = np.linspace(0,400,40000)
fig = plt.figure()
solution = odeint(rhs, IC, time_span)
X, Y = zip(*solution)
plt.plot(X, Y)
axes = plt.gca()
axXmin, axXmax = axes.get_xlim()
axYmin, axYmax = axes.get_ylim()
xmin = max(-15, axXmin)
xmax = min(15, axXmax)
ymin = max(-15, axYmin)
ymax = min(15, axYmax)
X,Y,U,V = npp.ezDomainQuiver2D([[xmin, xmax],[ymin, ymax]],[25,25],lambda X: rhs(X, 0),Normalize=True)
plt.quiver(X,Y,U,V)
plt.scatter([xeq],[yeq], color='red')
plt.xlim([xmin, xmax])
plt.ylim([ymin, ymax])
plt.axes().set_aspect('equal', 'datalim')
plt.show()
It work pretty well on my friend computer because he showed me the plots but I can't make it run in mine, I'm using Python 3.5.0cr1 Shell to run it out but it always came with te next error:
**Traceback (most recent call last):
File "C:\Users\PankePünke\Desktop\limites.py", line 1, in <module>
import np_plots as npp
ImportError: No module named 'np_plots'**
I'm totally new in Python programming and my friend made this program for me in order to make some advances in my thesis but I want to continue working with this program and get the plots from this. I do not know how to install or what kind of procceddure I should follow in order to get what I want (the plots and graphics that this program make) So... I'll be very thankful if somebody can help me in not a advance way, because how a wrote I'm totally new in Python, I just installed it and that is all.
You friend had a lib called np_plots on their computer, it is not part of the standard lib so you need to also install/get it on your comp or the code will not run. Most likely your friend actually wrote the code as I cannot see any mention of that lib anywhere so you will have to get it from them.
Apart from your friends lib, scipy and numpy are also not in the standard library, they do come with some distributions like Canopy but if you just installed a regular version of python you will need to install those also.
Might be worth checking out pip as it is the de-facto standard package manager for python.
I started to learn MatPlotLib using this tutorial for beginners. Here is the first example.
from pylab import *
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
If I write these 3 lines into my python file and execute it in the command line (by typing python file_name.py), nothing happens. No error message, no plot.
Does anybody know why I do not see the plot?
ADDED
Of course I need to use show. But even if I add the following 3 lines:
plot(X,C)
plot(X,S)
show()
it still does no generate anything.
ADDED
Here are the lines that I use now:
import pylab as p
C = [1,2,3,4]
S = [10, 20, 30, 10]
p.plot(C,S)
p.show()
I still have the same result (nothing).
It could be a problem with the backend.
What is the output of
python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)'?
If it is the 'agg' backend, what you see is the expected behaviour as it is a non-interactive backend that does not show anything to the screen, but work with plt.savefig(...).
You should switch to, e.g., TkAgg or Qt4Agg to be able to use show. You can do it in the matplotlib.rc file.
#shashank: I run matplotlib both on 12.04 and 12.10 without problems. In both cases I use the Qt4Agg backend. If you don't have the matplotlibrc set, the default backend is used.
I'm sure that for Precise matplotlib repo was built with TkAgg. If the Quantal version has been built with e.g. Agg, then that would explain the difference
You need to call the function:
show()
to be more exact:
pylab.show()
and even better don't use:
from pylab import *
rather do:
import pylab as p:
and then:
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
p.plot(C,S)
p.show()
Try adding. I use Jupyter and this worked for me.
%matplotlib inline