I am using VS Code and python. What happens is that in a program like:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1,10)
plt.plot(x, np.sin(x))
plt.show()
plt.plot(x, np.cos(x))
plt.show()
plt.plot(x, np.tan(x))
plt.show()
is that it will stop the exicution of the skript at line 5 and show the plot in a seperate window. It will only continiue to execute the program if I close the plot. Then it will continue until line 7 and stop there.
In other edidors I dont have this behaviour. Like in Spyder. There it will show the polt at the corresponding line, but it will continue the execution of the skript. Is there a way to make the same thing happen in VS Code?
A workaround would be to use plt.figure(). But I am forced to use templates were I can not change the plt.show()'s in the skript. So, I cant use this.
In VSCode, when running and debugging the code, the results will be executed in the same terminal and then output the results, so the above code is executed and output in sequence.
However, according to your description, it is recommended that you use the Jupyter notebook function in VSCode without changing your code. The results will be output in turn and then displayed together.
Use: "Ctrl+Shift+P", "Python: Create Blank New Jupyter Notebook", input the code.
Result:
Reference: Jupyter Notebooks in Visual Studio Code.
If this is not what you want, please describe it in detail and let me know.
Are you looking for this? It turns on "interactive mode". Plotting no longer blocks.
matplotlib.pyplot.ion()
With that, behaviour feels similar to plotting in R, even while in debug mode.
Related
I'm trying to open any matplotlib chart in the interactive mode in Python Interactive in vscode (Windows)
I tried to use magic
%matplotlib qt
and sometimes it works, but, very often, it just 'blinks' (open chart window and close it instantly, I don't know why) and shows chart in Python Interactive instead
I have tried plt.ion() but it seems that it doesn't change anything.
What is the right way of an opening chart in interactive mode?
If you want to show the plot in a separate window, you may need to set a backend. Also, your selected backend may not be compatible with your setup, so try a few.
In [4]: plt.switch_backend('QtAgg4')
If you DO want to show plots inline, you do not need to do anything. By default, VS Code will show the plots inline. You do not need %matplotlib inline, or plt.show(). If you DO want plots inline and it's not working, try:
get_ipython().run_line_magic('matplotlib', 'inline')
This is what shows up when you convert a jupyter notebook into VS Code by importing it.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,100)
y = x*2
# Functional Method
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.plot(x, y)
ax.set_title('title')
ax.set_xlabel('X')
ax.set_ylabel('Y')
My Code, tested on my VS Code in Interactive Window, with plot showing inline.
Updated answer as of Nov 2019:
This problem is gone with the recent update to VS Code. Make sure to install all Jupyter Notebook extensions. Also, you can now right-click on a .ipynb file and select "Open-With VS Code". This will automatically open the file in 2 windows, raw-json-code on left and interactive-jupyter-notebook on right. Slick. Really love this new update to VS Code.
I'm a developer on the Interactive Window. Jennifer has already given some good advice above for getting pop out plots working with our current builds. But if you are interested, we just recently added a plot viewer to our newest development builds. You can see the issue here:
https://github.com/microsoft/vscode-python/issues/4976
It won't be in our full release until our next monthly release. But if you want to try it out early and see if it works for you, you can check out our dev build here:
https://github.com/microsoft/vscode-python/blob/master/CONTRIBUTING.md#development-build
First of all, before this is tagged as duplicate, I have read the other solutions and unfortunately none of them worked for me.
My problem is that I want to display a bokeh plot in Juypter Notebook (and only in Jupyter Notebook), not in a new tab/window.
In the official documentation here I am told that I only need to change
output_file
to
output_notebook
Even though the plot is now displayed inline if I do that, bokeh won't stop also opening a new tab and needlessly displaying the plot there.
Since I'm gonna create lots of plots in my project, it'd be very nice to not always have to close this new tab and return to notebook, but just have it stop creating new tabs, just as it would work with e.g. matplotlib.
What confuses me is that if I load up the official tutorial and enter code there, for example
import numpy as np
x = np.linspace(0, 10, 100)
y = np.exp(x)
p = figure()
p.line(x, y)
show(p)
there is no new tab opened. If I now run the same code locally on my machine's Juypter Notebook, it does open up a new tab.
I've been trying for a while now to fix this, any help would be very much appreciated.
Thanks in advance, Vincent
You need to call output_notebook at the top of your notebook, but only call output_notebook. If you call output_file at all, that activates a persistent mode that saves output to files, and causes show to open new tabs with those files. You would need to call reset_output to clear that persistent mode.
As a convenience, since several users asked for it, if no output mode is supplied, show behaves as though output_file was called as a default. The reason a tab is not opened from the Binder tutorial is because it is not technically possible for code running remotely on Binder server to open a tab on your local browser (which is a very good thing).
Adding an explicit example to #bigreddot's answer:
You might have ran bokeh.io.output_file() somewhere in your notebook, to save noteable graphs. However, now you only want to experiment with some plots quickly to inspect the data.
Simply reset your settings to stop saving to file in any cell in your notebook like so:
import bokeh.io
# this is here only for completeness to clarify where
# the methods are nested (you probably already imported this earlier)
bokeh.io.reset_output()
bokeh.io.output_notebook()
You can activate saving to file again later to keep the interesting graphs.
You can import:
from bokeh.plotting import output_notebook
And call output_notebook before your figures declaration, then you just show the figure using show. See the doc.
I have spent over an hour searching, just to figure this simple thing. So, before considering this a duplicate question, please compare my question to any question out there.
This is my code:
import pandas
import matplotlib.pyplot as plt
dataset = pandas.read_csv('international-airline-passengers.csv', usecols=[1], engine='python', skipfooter=1)
print dataset, type(dataset)
plt.plot(dataset)
plt.show()
plt.close()
Firstly, plt.show() to my understanding is a blocking function. So what is the way to close the figure. There is no point in writing plt.close() after it. So where is the right way to put it.
Secondly, how can I make sure all the windows are closed when I execute a new process of the same python code. For example in MATLAB, one could easily say close all in the beginning of their file and it closes all the opened plots which were the result of previous MATLAB code execution. plt.close('all') is not working either.
I am using PyCharm. The results I found for the first situation, might work on IDLE but not in the PyCharm. How can I do it PyCharm.
plt.show(block=False) will do the trick- This is the way you can make this function non-blocking (both in run & debug mode). The main dis-advantage is that if the code ends, the figure is automatically closes...
I had the same problem.
I fix it making the python file in Pycharm to run in only one console. Go to: run---Edit configuration-- check that "single instance only" is activated
There are two ways to run matplotlib, non-interactive and interactive. In non-interactive mode, the default, you are right that plt.show() is blocking. In this case, calling plt.close() is pointless, the code won't stop as long as the figure is open. In interactive mode, however (which can be triggers by plt.ion()), this code will open then immediately close the figure. You would need to put something to wait for user input if you run code like this in a script. Interactive mode, as the name implies, is designed more for running interactively rather than in a script.
As for closing figures from multiple runs of a python script, this isn't possible. If you open multiple instances of MATLAB, close all in one instance won't close the figures in another instance. Running multiple processes of the same python code is the same as opening multiple instances of MATLAB, one run has no knowledge of the others.
This is highly related to an earlier question by another person a couple of years ago: Matplotlib - Force plot display and then return to main code
I am using Canopy 1.5.5 on MacOSX 10.8.5, with matplotlib 1.4.3.
I will need to load data, look at it, press enter to approve and move to the next dataset (and do that a few thousand times, so it's kind of critical to get this functionality). Here is my MWE:
import numpy as np
from matplotlib import pyplot as plt
plt.ion()
plt.figure()
ind=np.arange(5)
for i in ind:
plt.clf()
plt.scatter(ind,ind+i)
plt.title('this is plot number %i' % i)
plt.show()
u=raw_input("Press any button")
The code seems to do everything EXCEPT actually showing me the plot. If I finish the script (or interrupt it), then I see the current figure.
I have tried everything from the previous answer: with and without interactive mode, with and without plt.show(block=False), every permutation of plt.draw and plt.show, and every backend on my available list.
This seems like a very basic functionality! Please tell me that this can be done. I find it weird that matplolib says here http://matplotlib.org/users/shell.html that "by default the drawing is deferred until the end of the script", but does not have suggestions on how to override the default. Please help!
Your example works for me (my backend is osx), although the figure window appears behind other windows at first. I needed to use alt-tab to raise it to the front.
Try starting your script with the --matplotlib option of IPython. You can select a backend or let it be auto-detected like so: ipython --matplotlib auto yourscript.py
Not sure if you now, but the raw_input function waits for you to press the return key, not just any key.
Edit:
About your last remark: this section explains how to force drawing before the end of the script. This can be done with the draw function. In interactive mode every pyplot command calls draw as well. Drawing in this context means rendering the figure by the backend.
I am working in linux and I don't know why using python and matplotlib commands draws me only once the chart I want.
The first time I call show() the plot is drawn, wihtout any problem, but not the second time and the following.
I close the window showing the chart between the two calls. Do you know why and hot to fix it?
Thanks AFG
from numpy import *
from pylab import *
data = array( [ 1,2,3,4,5] )
plot(data)
[<matplotlib.lines.Line2D object at 0x90c98ac>]
show() # this call shows me a plot
#..now I close the window...
data = array( [ 1,2,3,4,5,6] )
plot(data)
[<matplotlib.lines.Line2D object at 0x92dafec>]
show() # this one doesn't shows me anything
in windows this works perfect:
from pylab import *
plot([1,2,3,4])
[<matplotlib.lines.Line2D object at 0x03442C10>]
#close window here
plot([1,2,3,4])
[<matplotlib.lines.Line2D object at 0x035BC570>]
did you try with:
from matplotlib import interactive
interactive(True)
sometimes matplotlib produces some headaches because we have to remember that some options are set in matplotlibrc (such as the backend or the interactive parameters). If you use matplotlib from different editors (IDLE-tk, pycrust-wxpython) or alternating interactive with scripting, then you have to take into account that the configuration that works in one mode could give you problems in the other mode and must be modified programmatically or using a dedicated configuration file.
The example I give, works directly (and without show()) because in matplotlibrc I have interactive set to True as default
You likely have conflicts between your editor/IDE windowing system, and your plot windows.
A very good way around this is to use IPython. IPython is a great interactive environment, and has worked out these issues plus has many other advantages. At the beginning, start IPython with the command (from a terminal window) ipython -pylab to put it in the interactive pylab mode.
I'm guessing that you are doing this in IDLE on Windows because that's where I've noticed this same problem.
From what I've deduced, there is a problem with using the TkAgg backend,which comes with the basic Python dist and appears to be the default for matplotlib, when using matplotlib with IDLE. It has something to do with the way IDLE uses subprocesses because if I start IDLE with the -n option, which disables subprocesses, I don't have this problem. An easy way to start it IDLE with the -n option on Windows is to right click and file and select 'Open with IDLE'. If you do this you should get an IDLE shell which says
=== No Subprocess ===
just above the prompt. For instance, borrowing code from joaquin's solution, you could try this simple code:
from matplotlib import interactive
interactive(True)
from pylab import *
plot([1,2,3,4])
then close the window and type the last line into the console again. It works for me in IDLE with the -n option.
So what can you do? You can always run IDLE in the mode without subprocesses, but there are dangers to that. You can use a different IDE. Many people suggest IPython though I'm not sold on it yet myself. You could also try a different backend for matplotlib. I'm going to try that in a little while cause I've been wondering whether it will work.
show() is only meant to be used once in a program, at the very end: it is a never ending loop that checks for events in the graphic windows.
The normal way of doing what you want is:
# … plot …
draw() # Draws for real
raw_input() # Or anything that waits for user input
# … 2nd plot …
draw()
raw_input()
# Last plot
show() # or, again, draw(); raw_input()
You could try to see whether this works for you.
Alternatively, you can try to change the backend, as some backends work better than others:
import matplotlib
matplotlib.use('TkAgg') # For other backends, do matplotlib.use('') in a shell