No plot shows up from VS Code - python

I initiated the VS Code window through a WSL Ubuntu terminal such as
/mnt/d/github/python/python_for_data_science$ code .
And test a plot
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 11)
y = x**2
# functional
plt.plot(x, y)
plt.show()
By Run Python File in Terminal, it shows
/mnt/d/github/python/python_for_data_science$ /usr/bin/python /mnt/d/github/python/python_for_data_science/section_8_matplotlib.py
But I didn't see a plot. Have I missed something?

WSL might not have the ability to show UI. Alternatively you can run the code in the Python Interactive window in order to see the output. Try right-click and select Run Current File in Python Interactive window.

Related

Spyder isn't graphing in the Console. Works fine with iPython, though

Here is some test code I am attempting in Spyder with Python 3.4.3. It runs just fine in iPython, but when I run in the console, the pop-up graph freezes and never displays. What's going on here??
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.cos(x)
plt.plot(x, y)

matplotlib plot doesn't appear even after editing the backend and using pylab.show()

I have a simple script to test a plot in matplotlib but no window showing the figure appears. On reading other questions on stackoverflow, I've done the following to resolve this:
installed PySide using these instructions.
edited matplotlibrc file with these two lines:
backend : Qt4Agg
#backend.qt4 : PySide # PyQt4 | PySide
so that the command python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)' now yields Qt4Agg whereas before it gave agg
included the pylab.show() command. So the set of commands that I now tried in the python interpreter after installing Pyside, and editing the matplotlibrc file look like this:
import pylab
pylab.ion()
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,5,0.1)
y = np.sin(x)
plt.plot(x,y)
[<matplotlib.lines.Line2D object at 0x7fcef627cdd0>]
pylab.show()
However, the plot still doesn't show. Could anyone please help me with this? I am using Ubuntu 14.04 in VirtualBox with python2.7.
When I use your code the plot actually flashes on the screen, but closes immediately. Placing an input() function at the end might help you with debugging it:
import pylab
import matplotlib.pyplot as plt
import numpy as np
pylab.ion()
x = np.arange(0,5,0.1)
y = np.sin(x)
plt.plot(x,y)
pylab.show()
tin = input("Test Input: ")
And removing the pylab.ion() actually keep the plot on the screen. This gives you another hint. There are already some good answers why this is happening. E.g.:
Matplotlib ion() function fails to be interactive

How to prevent ipython shutting down interactive mode while running a script

This page talks about the usage of ipython for interactive plotting: http://matplotlib.org/users/shell.html
According to that page, by default the %run command that is used to run scripts in ipython shuts down interactive mode. Is there an option to run the script in interactive mode as well?
I want the plotting commands in a script to take effect in the plotting figure as soon as they are run as if they are entered from the console interactively.
For example, consider the very simple script below:
# try.py:
# run in ipython that is started with
# ipython --pylab
# using
# %run -i try.py
from numpy import *
from time import sleep
ion()
x = randn(10000)
hist(x,100)
show()
sleep(5)
xlabel('labalu')
When run from ipython as indicated in the comment, this script waits 5 seconds, than shows everything. What I want is this: When run from ipython as indicated in the comment, the script should show the histogram immediately, wait 5 seconds, than update the figure to show the x label.
Moving ion() so it is after show() does what I think you want. Why it doesn't in the higher position, I do not know offhand.
If wx is used as the backend, following works:
#run in ipython that is started with ipython --pylab=wx
from numpy import *
import matplotlib
matplotlib.use('WX')
import wx
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
x = np.random.uniform(0,1,100)
plt.plot(x)
plt.show()
wx.Yield()
for i in reversed(range(5)):
print(i)
sleep(1)
plt.xlabel('labl')
wx.Yield()
So, wx.Yield() lets interaction with the figure window. This also works when the script is run with normal python, but the figure is closed at the end of the script automatically.
Any cross-backends solutions (or solutions for qt/tk ) are still well come.
And below is a solution that works with both the wx and qt backends. gcf().canvas.flush_events() does the trick.
# try.py:
# run in ipython that is started with
# ipython --pylab
# using
# %run -i try.py
from numpy import *
import matplotlib
from time import sleep
x = randn(10000)
hist(x,100)
show()
ion()
gcf().canvas.flush_events()
sleep(5)
xlabel('labalu')
show()

matplotlib on mac doesn't display

There are a lot of questions about installing matplotlib on mac, but as far as I can tell I've installed it correctly using pip and it's just not working. When I try and run a script with matplotlib.pyplot.plot(x, y) nothing happens. No error, no nothing.
import matplotlib.pyplot
x = [1,2,3,4]
y = [4,3,2,1]
matplotlib.pyplot.plot(x, y)
When I run this in the terminal in a file called pyplot.py I get this:
pgcudahy$ python pyplot.py
pgcudahy$
No errors, but no plot either. In an interactive python shell I get this:
>>> import matplotlib
>>> print matplotlib.__version__
1.1.1
>>> print matplotlib.__file__
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.pyc
Which leads me to believe it's installed correctly.
Any ideas?
You need to call the show function.
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [4,3,2,1]
plt.plot(x, y)
plt.show()
It's likely that the plot is hidden behind the editor window or the spyder window on the screen. Instead of changing matplotlib settings, just learn the trackpack gestures of the mac, "app exposé" is the one you need to make your plots visible (see system preferences, trackpack). Then click on the figure to raise it to the front.

make matplotlib plotting window pop up as the active one

I'm working with python and matplotlib on mac os x.
When I'm working on many different windows and I have to run a script which produces a plot, the plot window always open behind the active window and is very frustration having to switch between windows for looking at the image.
Is it any why to decide the location of the plot window, and/or pop up it as foreground window?
thanks
For me (OSX 10.10.2, Matplotlib 1.4.3), what works is changing the matplotlib backend to TkAgg. Before importing pyplot or anything, go:
import matplotlib
matplotlib.use('TkAgg')
Plot windows now pop-up, and can be Command-Tab'ed to.
I was bothered by exactly the same problem. I found finally a solution (in pylab mode, with qt4agg backend):
get_current_fig_manager().window.raise_()
or
fig = gcf()
fig.canvas.manager.window.raise_()
Regards,
Markus
I found this solution was so often needed (e.g. when using Spyder IDE), I wrapped it into a function.
def show_plot(figure_id=None):
if figure_id is None:
fig = plt.gcf()
else:
# do this even if figure_id == 0
fig = plt.figure(num=figure_id)
plt.show()
plt.pause(1e-9)
fig.canvas.manager.window.activateWindow()
fig.canvas.manager.window.raise_()
I found a good answer on this thread:
How to make a Tkinter window jump to the front?
Basically, the idea is to use window attributes - set the '-topmost' attribute to True (1) to make the window come to the foreground, and then set it to False (0) so that it later allows other windows to appear in front of it. Here's code that worked for me:
import matplotlib.pyplot as plt
wm = plt.get_current_fig_manager()
wm.window.attributes('-topmost', 1)
wm.window.attributes('-topmost', 0)
For MacOS Sierra and python 3.6, Matplotlib 2.0.0
import matplotlib.pyplot as plt
plt.get_current_fig_manager().show()
the above line does the job no need of anything else.
This worked for me!!
(Tested on Mac OS X 10.11, Spyder 2.3.5.2 - Python 3.4)
Go to Preferences > IPython console > Graphics and set a backend to Qt (after that you need to restart the kernel).
Make a file that contains:
def raise_window(figname=None):
if figname: plt.figure(figname)
cfm = plt.get_current_fig_manager()
cfm.window.activateWindow()
cfm.window.raise_()
and import it at startup (Preferences > IPython console > Startup > Run a file). Now, just call function raise_window() below your code.
Example:
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
plt.figure()
plt.plot(X, C)
plt.plot(X, S)
raise_window()
For me only the following works (with TkAgg backend):
plt.gcf().canvas.get_tk_widget().focus_force()
As of matplotlib 1.5.1 on MacOSX 10.11.6, if you start an iPython (5.0.0, Python: 3.5.2) shell and use %matplotlib you can bring a matplotlib plot to the front using:
>>> %matplotlib
Using matplotlib backend: MacOSX
>>> import matplotlib.pyplot as plt
>>> plt.plot([1,3,2,4])
>>> plt.show()
** Edit: Advice seems to be not to use %pylab as it pollutes the global name space **
.. shell and use %pylab you can bring a matplotlib plot to the front using:
>>> %pylab
Using matplotlib backend: MacOSX
Populating the interactive namespace from numpy and matplotlib
>>> plot([1,3,2,4])
>>> show()
You can set
backend : MacOSX
in your matplotlibrc file for a permanent solution.
It works for me on macos mojave, with matplotlib 2.1.2. However, other users have complained that it does not work for them, so it might be affected by other settings
The following worked on Jupyter notebook with Qt5 backend on Windows. I tested it with Python 3.7, matplotlib 3.2.1.
%matplotlib qt5
import matplotlib.pyplot as plt
import numpy as np
from PyQt5 import QtCore
plt.plot(np.linspace(0,1))
window = plt.get_current_fig_manager().window
window.setWindowFlags(window.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
plt.show()
window.setWindowFlags(window.windowFlags() & ~QtCore.Qt.WindowStaysOnTopHint)
plt.show()

Categories

Resources