This question already has an answer here:
Matplotlib: how to show a figure that has been closed
(1 answer)
Closed 3 years ago.
Is it possible to re-open a closed figure (i.e., one the user X'd) in matplotlib? The following code shows the naive approach:
In [14]: fig = figure(10)
In [15]: close(fig)
In [16]: fig.show()
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__
return self.func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 495, in callit
func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/backends/backend_tkagg.py", line 253, in idle_draw
self.draw()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/backends/backend_tkagg.py", line 239, in draw
tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/backends/tkagg.py", line 19, in blit
tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array))
TclError: this isn't a Tk application
I'm trying to create a figure with widgets in it, so a workaround is available (just make a new figure), but I would like to know if the figure instance is totally useless after being closed.
Yes, closing the figure deletes it completely.
Related
I am using Python 3.7. I would like to change my backend temporarily so that I can zoom in/out of my data. However, generating figures using qt backend gives me a ValueError, even if the figure is minimally simple.
Here is a minimum example, where I typed the following commands in the console one by one
[Input Commands]
import matplotlib.pyplot as plt
%matplotlib qt
plt.plot([1,2],[1,2])
[Output Error]
[<matplotlib.lines.Line2D at 0x1b2efda7648>]Traceback (most recent call last):
File "C:\Users\USER_NAME\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 455, in _draw_idle
self.draw()
File "C:\Users\USER_NAME\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py", line 431, in draw
self.renderer = self.get_renderer(cleared=True)
File "C:\Users\USER_NAME\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py", line 447, in get_renderer
self.renderer = RendererAgg(w, h, self.figure.dpi)
File "C:\Users\USER_NAME\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py", line 93, in __init__
self._renderer = _RendererAgg(int(width), int(height), dpi)
ValueError: Image size of 213120x159840 pixels is too large. It must be less than 2^16 in each direction.
I don't think this question is a duplicate of previous questions (here and here) because the error appears even for a very simple figure with no labels.
I thought I had accidentally overwritten some kind of setting file, so I tried re-installing matplotlib using
"conda install matplotlib" at the Anaconda prompt, but it didn't help. Changing back to my default backend "%matplotlib inline" generates figures normally.
How can I fix my qt backend?
I am currently developing a GUI in Python using PySimpleGUI and am working on plotting some graphs in frames contained by the main window. I succeeded in doing this using this example code1 and it looks fine. However, when I close the main window after having plotted a graph, I get the following list of errors related to Tkinter:
Exception in Tkinter callback\
Traceback (most recent call last):\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 1705, in __call__\
return self.func(*args)\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 3072, in set\
self.tk.call(self._w, 'set', first, last)\
_tkinter.TclError: invalid command name\ ".!toplevel.!frame.!notebook.!frame4.!frame4.!tkscrollableframe.!scrollbar2"\
Exception in Tkinter callback\
Traceback (most recent call last):\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 1705, in __call__\
return self.func(*args)\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 3072, in set\
self.tk.call(self._w, 'set', first, last)\
_tkinter.TclError: invalid command name\ ".!toplevel.!frame.!notebook.!frame4.!frame4.!tkscrollableframe.!scrollbar"\
Exception in Tkinter callback\
Traceback (most recent call last):\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 1705, in __call__\
return self.func(*args)\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 3072, in set\
self.tk.call(self._w, 'set', first, last)\
_tkinter.TclError: invalid command name\ ".!toplevel.!frame.!notebook.!frame4.!frame4.!tkscrollableframe.!scrollbar2"\
Exception in Tkinter callback\
Traceback (most recent call last):\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 1705, in __call__\
return self.func(*args)\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 3072, in set\
self.tk.call(self._w, 'set', first, last)\
_tkinter.TclError: invalid command name\ ".!toplevel.!frame.!notebook.!frame4.!frame4.!tkscrollableframe.!scrollbar"\
I am new to matplotlib and haven't used Tkinter before, but would like to know the cause of these errors, if anyone knows. My code is quite big, but I can add it to the post if necessary.
I have tried commenting different parts of my code to find the culprit and when I remove the line corresponding to the following in the demo I used, the errors stopped:
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
Have anyone experienced this problem before? I am running this on a machine running Centos and have tried running a simpler program in Windows, which closes without any problem.
Thanks in advance.
EDIT 1: Upon request I have just added the simplest Python code I could produce that reproduces this kind of error:
import PySimpleGUI as sg
import matplotlib as mp
from matplotlib import figure
from matplotlib.backends import backend_tkagg
import numpy as np
layout1 = [
[
sg.Frame("Frame",
[
[
sg.Column(
[
[sg.Canvas(key="-CANVAS-")]
],
size=(1000,1000)
)
]
]
)
]
]
layout2 = [
[sg.Column(layout1, scrollable=True)]
]
window = sg.Window("Window", layout2)
window.finalize()
x = np.array(list(range(10)))
fig = figure.Figure()
ax = fig.add_axes((0,0,1,1))
ax.plot(x, x)
figure_canvas_tkagg = backend_tkagg.FigureCanvasTkAgg(fig, master=window["-CANVAS-"].TKCanvas)
figure_canvas_tkagg.draw()
figure_canvas_tkagg.get_tk_widget().pack()
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
window.close()
It appears that it might have something to do with the fact that my GUI code consists of many levels of container-objects within cointainer-objects. In my full code I have a couple of layers on top of this, but the error seemed to appear once I made the following hierarchy:
Column
Frame
Column
Canvas
It should be noted that using the debugger of Visual Studio Code I have found out that the error does not occur exactly when the window closes (when the window.close() method is called), but some time before.
EDIT 2: I just tested it and for some reason this error only occurs when I run the attached Python script on my Centos machine and not in Windows.
EDIT 3: I found out that if I close all the figures I have created before I close the window, these errors will not occur. This is not a complete fix however, since the error occur before the window.close() command of PySimpleGUI is run, so I don't know where to put the code that would close the figures in case the window is closed.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to use sklearn GridSearchCV to perform K-fold cross-validation to select a bandwidth for KernelDensity estimation.
When I implement grid.fit(data), I receive the error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Users\mubar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sklearn\utils\validation.py", line 73, in inner_f
return f(**kwargs)
File "C:\Users\mubar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sklearn\model_selection\_search.py", line 736, in fit
self._run_search(evaluate_candidates)
File "C:\Users\mubar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sklearn\model_selection\_search.py", line 1188, in _run_search
evaluate_candidates(ParameterGrid(self.param_grid))
File "C:\Users\mubar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sklearn\model_selection\_search.py", line 714, in evaluate_candidates
in product(candidate_params,
File "C:\Users\mubar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sklearn\model_selection\_split.py", line 80, in split
for test_index in self._iter_test_masks(X, y, groups):
AttributeError: 'numpy.ndarray' object has no attribute '_iter_test_masks'
Here is my code:
import numpy as np
from sklearn.model_selection import GridSearchCV, LeaveOneOut
train = np.random.rand(12,2)
target = np.array([0,0,1,2,3,3,3,4,5,5,6,6])
bw = np.linspace(0.01,0.1,10)
grid = GridSearchCV(KernelDensity(kernel='gaussian'),
{'bandwidth': bw},
cv=LeaveOneOut)
grid.fit(train,target[:,None])
You just forgot to instantiate the LeaveOneOut cross-validator in your GridSearchCV definition.
train = np.random.rand(12,2)
target = np.array([0,0,1,2,3,3,3,4,5,5,6,6])
bw = np.linspace(0.01,0.1,10)
grid = GridSearchCV(KernelDensity(kernel='gaussian'),
{'bandwidth': bw},
cv=LeaveOneOut() # <-- typo was here
)
grid.fit(train,target[:,None])
This will resolve the issue.
I am attempting to execute the following within python:
from pandas import *
tickdata = read_csv('/home/user/sourcefile.csv',index_col=0,parse_dates='TRUE')
The csv files has rows that look like:
2011/11/23 23:56:00.554389,1165.2500
2011/11/23 23:56:02.310943,1165.5000
2011/11/23 23:56:05.564009,1165.2500
On pandas .7, this executes fine. On pandas .8.0rc2, I get the error below. Because I have .7 and .8 installed on two different systems, I have not ruled out a dependency or python version difference. Any ideas on how to get this to execute under .8 are appreciated.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pandas-0.8.0rc2-py2.7-linux-x86_64.egg/pandas/io/parsers.py", line 225, in read_csv
return _read(TextParser, filepath_or_buffer, kwds)
File "/usr/local/lib/python2.7/dist-packages/pandas-0.8.0rc2-py2.7-linux-x86_64.egg/pandas/io/parsers.py", line 192, in _read
return parser.get_chunk()
File "/usr/local/lib/python2.7/dist-packages/pandas-0.8.0rc2-py2.7-linux-x86_64.egg/pandas/io/parsers.py", line 728, in get_chunk
index = self._agg_index(index)
File "/usr/local/lib/python2.7/dist-packages/pandas-0.8.0rc2-py2.7-linux-x86_64.egg/pandas/io/parsers.py", line 846, in _agg_index
if try_parse_dates and self._should_parse_dates(self.index_col):
File "/usr/local/lib/python2.7/dist-packages/pandas-0.8.0rc2-py2.7-linux-x86_64.egg/pandas/io/parsers.py", line 874, in _should_parse_dates
return i in to_parse or name in to_parse
TypeError: 'in <string>' requires string as left operand, not int
I fixed the parser bug shown in the stack trace that you pasted. However, I'm wondering whether your date column is named "TRUE" or did you mean to just pass a boolean? I haven't dug through pandas history but I know that in 0.8 we are supporting much more complex date parsing behavior as part of the time series API so here we're interpreting the string value as a column name.
I've reported the bug on GitHub (best place for bug reports):
https://github.com/pydata/pandas/issues/1544
Should have a resolution today or tomorrow.
All parts of Python on my computer were recently installed from the Enthought academic package, but use Pyscripter for editing and running code. I'm very early in my learning curve, and so could very well be overlooking some obvious things here.
When I try to create a plot and save it like so:
import matplotlib.pylab as pl
pl.hist(myEst, bins=20, range=(.1,.60))
pl.ylabel("Freq")
pl.xlabel("Success Probability")
pl.title('Histogram of Binomial Estimator')
pl.axis([0, 1, 0, 500])
pl.vlines (.34,0,500)
pl.savefig('TestHist.png')
pl.show()
I get these errors:
Traceback (most recent call last):
File "<editor selection>", line 9, in <module>
File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1172, in savefig
self.canvas.print_figure(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_wxagg.py", line 100, in print_figure
FigureCanvasAgg.print_figure(self, filename, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 2017, in print_figure
**kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 450, in print_png
filename_or_obj = file(filename_or_obj, 'wb')
IOError: [Errno 13] Permission denied: 'TestHist.png'
If I take out the pl.savefig('TestHist') line everything works fine, and I can see the plot I want, but when that line is in there I get the errors.
I've checked my backend version using pl.get_backend(), it returns 'WXAgg', which according to documentation should be able to use .png format.
I've also tried including an explicit format='png' and format=png within the savefig command, but still get errors.
Can anyone give me advice on how to proceed, or another approach for saving a plot?
There's nothing wrong with your code. I just tested it locally on my machine. The issue is this error:
IOError: [Errno 13] Permission denied: 'TestHist.png'
You are most likely trying to save the file somewhere that the Python process doesn't have permission to access. What OS are you on? Where are you trying to save the file?
If it helps others, I made the silly mistake of not actually designating a file name and as a result had returned the same error message that lead me to this question for review.
Here is the code that was generating the error:
plt.savefig('C:\\Users\\bwarn\\Canopy', format='png')
Here is my correction that resolved (you'll see I designated the actual file and name)
plt.savefig('C:\\Users\\bwarn\\Canopy\\myplot.png', format='png')
The following worked for me when I was running a neural network on my windows machine:
image_path = 'A:/DeepLearning/Padhai/MLFlow/images/%s.png' % (expt_id)
plt.savefig(image_path)
Or otherwise refer:
Using 'r' in front of the path