I have a problem with ploting in Python
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.arange(10),np.arange(10))
plt.show(0)
#another computation
I am using Spyder editor with graphic backend set to automatic. I want to make plot in new window. The problem is the plot appear after the end of the script. How to make it appear immediately?
Related
I am having a really weird issue with using the %matplotlib inline code in my jupyter notebook for plotting graphs using both pyplot and the pandas plotting function.
The problem is they show up without any axes, and basically just show the graph area without anything aside from data points.
I found adding:
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)
reverse it, but I find it odd that should do that every time as the effect disappears as soon as I run %matplotlib inlinecommand.
an example could be
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(A,A)
plt.tight_layout()
plt.xlabel('here')
plt.show()
This would generate the graph below:
Weird enough if I uses the savefig it get plotted with the axis, if I uses the right-click -> new output -> save as figure, I also get the graph with the figures !!
like this:
Can anyone help me understand what is wrong, which global setting did I mess up, and how do I revert it?
(I don't remember messing around with any settings aside from some settings for pandas, but don't think they should have had an impact)
as mentioned running mpl.rcParams.update(mpl.rcParamsDefault) command does bring it back to normal until I run %matplotlib inline` again !!
Any help would be much appreciated.
Okay I am sorry I think I can answer the question myself now.
With the helpfull #Mr. T asking for the imgur link made me realize what was going on. I had starting using the dark jupyter lab theme, and the graph would generate plots with transparent background, ie. the text and lines where there, but I just couldn't see them.
The trick is to change the background color preferably globally, but that will be a task for tomorrow.
I'm using getdist to plot some simulation results.
In jupyter writing just this line
g = plots.getSubplotPlotter()
g.triangle_plot([samples, samples2], filled=True)
Python will show plots as we can see here.
Now if we want to write it in Python shell and run it with IDLE, this does not produce any plot. plt.show() does not work here.
How to instruct python or matplotlib to show the plots and save them?
The problem is that getdist sets the backend to Agg (in this line), which is a non-interactive backend and hence cannot produce an interactive figure via plt.show().
This is pretty bad style, because the user should select the backend, not the package. You might want to inform the developpers about this design flaw.
Anyways it would be possible to switch the backend after importing getdist, via plt.switch_backend(..). As backend you would need to use any interactive backend you have available, e.g. "Qt5Agg" or "TkAgg".
import numpy as np
from getdist import plots, MCSamples
import matplotlib.pyplot as plt
plt.switch_backend("Qt5Agg")
# .. some code ..
g = plots.getSubplotPlotter()
g.triangle_plot([samples, samples2], filled=True)
plt.show()
I am using PyCharm as the IDE for python, and when you make a plot (with the same code like pyplot.plot(...), pyplot.show()) pycharm displays it within its IDE. However, this looks like a static image. When you zoom in, the plot starts to blur.
In other IDE, pyplot creates an interactive plot. When you zoom in, it basically re-plots the curve. And you can also drag the plot. Is there anyway in PyCharm I can have the interactive plot from pyplot?
Just need to change your plotting backend.
If you're on macOS:
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use('macosx')
plt.plot(range(10))
should produce a new window that looks like this:
Or if you prefer a different backend or are on Windows (as #MichaelA said)
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use('Qt5Agg') # or can use 'TkAgg', whatever you have/prefer
plt.plot(range(10))
import matplotlib.pyplot as plt
plt.plot([1,2,3],[1,2,3],'ro')
plt.axis([-4,4,-4,4])
plt.savefig('azul.png')
plt.plot([0,1,2],[0,0,0],'ro')
plt.axis([-4,4,-4,4])
plt.savefig('amarillo.png')
Output:
Why does this happen and how to solve?
What you see is a completely expected behaviour. You can plot as many data as often as you want to the same figure, which is very often very useful.
If you want to create several figures in the same script using the matplotlib state machine, you need to first close one figure before generating the next.
So in this very simple case, just add plt.close() between figure creation.
import matplotlib.pyplot as plt
plt.plot([1,2,3],[1,2,3],'bo')
plt.axis([-4,4,-4,4])
plt.savefig('azul.png')
plt.close()
plt.plot([0,1,2],[0,0,0],'yo')
plt.axis([-4,4,-4,4])
plt.savefig('amarillo.png')
I'm asking this question because I can't solve one problem in Python/Django (actually in pure Python it's ok) which leads to RuntimeError: tcl_asyncdelete async handler deleted by the wrong thread. This is somehow related to the way how I render matplotlib plots in Django. The way I do it is:
...
import matplotlib.pyplot as plt
...
fig = plt.figure()
...
plt.close()
I extremely minimized my code. But the catch is - even if I have just one line of code:
fig = plt.figure()
I see this RuntimeError happening. I hope I could solve the problem, If I knew the correct way of closing/cleaning/destroying plots in Python/Django.
By default matplotlib uses TK gui toolkit, when you're rendering an image without using the toolkit (i.e. into a file or a string), matplotlib still instantiates a window that doesn't get displayed, causing all kinds of problems. In order to avoid that, you should use an Agg backend. It can be activated like so --
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot
For more information please refer to matplotlib documentation -- http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server
The above (accepted) answer is a solution in a terminal environment. If you debug in an IDE, you still might wanna use 'TkAgg' for displaying data. In order to prevent this issue, apply these two simple rules:
everytime you display your data, initiate a new fig = plt.figure()
don't close old figures manually (e.g. when using a debug mode)
Example code:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data[:,:,:3])
plt.show()
This proves to be the a good intermediate solution under MacOS and PyCharm IDE.
If you don't need to show plots while debugging, the following works:
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
However, if you would like to plot while debugging, you need to do 3 steps:
1.Keep backend to 'TKAgg' as follows:
import matplotlib
matplotlib.use('TKAgg')
from matplot.lib import pyplot as plt
or simply
import matplotlib.pyplot as plt
2.As Fábio also mentioned, you need to add fig(no. #i)=plt.figure(no.#i) for each figure #i. As the following example for plot no.#1, add:
fig1 = plt.figure(1)
plt.plot(yourX,yourY)
plt.show()
3.Add breakpoints. You need to add two breakpoints at least, one somewhere at the beginning of your codes (before the first plot), and the other breakpoint at a point where you would like all plots (before to the second breakpoint) are plotted. All figures are plotted and you even don't need to close any figure manually.
For me, this happened due to parallel access to data by both Matplotlib and by Tensorboard, after Tensorboard's server was running for a week straight.
Rebotting tensorboard tensorboard --logdir . --samples_per_plugin images=100 solved this for me.
I encountered this problem when plotting graphs live with matplotlib in my tkinter application.
The easiest solution I found, was to always delete subplots. I found you didn't need to instantiate a new figure, you only needed to delete the old subplot (using del subplot), then remake it.
Before plotting a new graph, make sure to delete the old subplot.
Example:
f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111)
(For Loop code that updates graph every 5 seconds):
del a #delete subplot
a = f.add_subplot(111) #redefine subplot
Finding this simple solution to fix this "async handler bug" was excruciatingly painful, I hope this helps someone else :)