Related
I'm using
PyCharm 2021.2.3 Community Edition
Python interpreter 3.10.0
matplotlib 3.5.0
seaborn 0.11.2
numpy 1.21.4
pandas 1.3.4
PySimpleGUI 4.55.1
When I run the following script, it is fine in run mode but in debug mode it throws an exception. Here's the script:
import numpy as np
import pandas as pd
import PySimpleGUI as sg
import seaborn as sns
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
def init_data():
r1 = np.random.rand(5, 4)
columns = [f"var{i}" for i in range(1, 5)]
df = pd.DataFrame(r1, columns=columns)
df.insert(0, 'year', range(2021, 2026))
df.insert(1, 'scenario', 'test1')
ldf = pd.melt(df, id_vars=['year', 'scenario'], value_vars=columns, var_name='percentile', value_name='carbon')
return ldf
def draw_figure(canvas, figure):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
return figure_canvas_agg
# define the window layout
layout = [[sg.Text('Plot test')],
[sg.Canvas(key='-CANVAS-')],
[sg.Button('Ok')]]
# create the form and show it without the plot
window = sg.Window('Testing seaborn in PySimpleGUI', layout, finalize=True,
element_justification='center', font='Helvetica 18')
figure = Figure()
ax = figure.subplots()
sns.lineplot(x='year', y='carbon', hue='percentile', data=init_data(), ax=ax)
# add the plot to the window
fig_canvas_agg = draw_figure(window['-CANVAS-'].TKCanvas, figure)
event, values = window.read()
window.close()
And here's the stacktrace:
Traceback (most recent call last):
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\numpy\core\getlimits.py", line 384, in __new__
dtype = numeric.dtype(dtype)
TypeError: 'NoneType' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2.3\plugins\python-ce\helpers\pydev\pydevd.py", line 1483, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "D:/OneDrive/OneDrive - Louise Pryor & Co Ltd/Actuarial/Carbon/Carbon/seaborntest.py", line 39, in <module>
sns.lineplot(x='year', y='carbon', hue='percentile', data=init_data(), ax=ax)
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
return f(**kwargs)
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\seaborn\relational.py", line 710, in lineplot
p.plot(ax, kwargs)
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\seaborn\relational.py", line 557, in plot
self._add_axis_labels(ax)
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\seaborn\_core.py", line 1194, in _add_axis_labels
x_visible = any(t.get_visible() for t in ax.get_xticklabels())
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axes\_base.py", line 75, in wrapper
return get_method(self)(*args, **kwargs)
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axis.py", line 1249, in get_ticklabels
return self.get_majorticklabels()
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axis.py", line 1201, in get_majorticklabels
ticks = self.get_major_ticks()
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axis.py", line 1371, in get_major_ticks
numticks = len(self.get_majorticklocs())
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axis.py", line 1277, in get_majorticklocs
return self.major.locator()
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\ticker.py", line 2113, in __call__
vmin, vmax = self.axis.get_view_interval()
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axis.py", line 1987, in getter
return getattr(getattr(self.axes, lim_name), attr_name)
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axes\_base.py", line 781, in viewLim
self._unstale_viewLim()
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axes\_base.py", line 776, in _unstale_viewLim
self.autoscale_view(**{f"scale{name}": scale
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axes\_base.py", line 2932, in autoscale_view
handle_single_axis(
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axes\_base.py", line 2895, in handle_single_axis
x0, x1 = locator.nonsingular(x0, x1)
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\ticker.py", line 1654, in nonsingular
return mtransforms.nonsingular(v0, v1, expander=.05)
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\transforms.py", line 2880, in nonsingular
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
File "C:\Users\drlou\AppData\Local\Programs\Python\Python310\lib\site-packages\numpy\core\getlimits.py", line 387, in __new__
dtype = numeric.dtype(type(dtype))
TypeError: 'NoneType' object is not callable
Has anyone seen this before or have any ideas?
I had the same issue until I changed my version of python from 3.10 to 3.9.5.
This did the ugly trick for debugging under pyCharm 2022.1.1, python 3.10.4, scipy=1.8.0
numpy=1.22.3
pandas=1.4.1
AK lame handling of debugg issue with numpy vs pandas/scipy np.core.numeric.dtype
if sys.gettrace():
np.core.numeric.dtype = np.dtype
I am trying to modify the plot shown in this answer, but replacing the fill_between with violin plots at each tick.
A naive implementation made me try following,
import matplotlib.pylab as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = np.linspace(1,5,100)
y1 = np.ones(x.size)
y2 = np.ones(x.size)*2
y3 = np.ones(x.size)*3
z = np.sin(x/2)
plt.figure()
ax = plt.subplot(projection='3d')
ax.plot(x, y1, z, color='r')
ax.plot(x, y2, z, color='g')
ax.plot(x, y3, z, color='b')
handle = plt.violinplot(x)
ax.add_collection3d(handle, zs=1, zdir='y')
The error that pops up is: AttributeError: 'PolyCollection' object has no attribute 'do_3d_projection'.
The error origin can be traced by the following log:
runcell(7, 'Figure.py')
Traceback (most recent call last):
File "Figure.py", line 163, in <module>
ax.add_collection3d(handle, zs=1, zdir='y')
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 2252, in add_collection3d
super().add_collection(col)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\axes\_base.py", line 1921, in add_collection
label = collection.get_label()
AttributeError: 'dict' object has no attribute 'get_label'
Traceback (most recent call last):
File "C:\Users\sarth\AppData\Roaming\Python\Python36\site-packages\IPython\core\formatters.py", line 341, in __call__
return printer(obj)
File "C:\Users\sarth\AppData\Roaming\Python\Python36\site-packages\IPython\core\pylabtools.py", line 248, in <lambda>
png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
File "C:\Users\sarth\AppData\Roaming\Python\Python36\site-packages\IPython\core\pylabtools.py", line 132, in print_figure
fig.canvas.print_figure(bytes_io, **kw)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\backend_bases.py", line 2193, in print_figure
self.figure.draw(renderer)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\artist.py", line 41, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\figure.py", line 1864, in draw
renderer, self, artists, self.suppressComposite)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\image.py", line 131, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\artist.py", line 41, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 447, in draw
reverse=True)):
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 446, in <lambda>
key=lambda col: col.do_3d_projection(renderer),
AttributeError: 'PolyCollection' object has no attribute 'do_3d_projection'
<Figure size 432x288 with 1 Axes>
Also tried using individual body objects using plt.violinplot(x)['objects'][i] but the same error is returned.
I recently switched to Matplotlib 3.3.1 and my old script start to complain. I guess it is an issue with cartopy. Here is a minimum reproducible example
import cartopy.crs as ccrs
fig, ax = plt.subplots(2, 2,
subplot_kw=dict(projection=ccrs.PlateCarree()),
figsize=[12,7], sharex=True, sharey=True)
plt.tight_layout()
Any suggestion to fix this issue?
Here I copy the error message:
Traceback (most recent call last):
File "", line 4, in
plt.tight_layout()
File
"C:\Users\Vinod\anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py",
line 451, in wrapper
return func(*args, **kwargs)
File
"C:\Users\Vinod\anaconda3\lib\site-packages\matplotlib\pyplot.py",
line 1490, in tight_layout
gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
File
"C:\Users\Vinod\anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py",
line 411, in wrapper
return func(*inner_args, **inner_kwargs)
File
"C:\Users\Vinod\anaconda3\lib\site-packages\matplotlib\figure.py",
line 2613, in tight_layout
kwargs = get_tight_layout_figure(
File
"C:\Users\Vinod\anaconda3\lib\site-packages\matplotlib\tight_layout.py",
line 303, in get_tight_layout_figure
kwargs = auto_adjust_subplotpars(fig, renderer,
File
"C:\Users\Vinod\anaconda3\lib\site-packages\matplotlib\tight_layout.py",
line 84, in auto_adjust_subplotpars
bb += [ax.get_tightbbox(renderer, for_layout_only=True)]
File
"C:\Users\Vinod\anaconda3\lib\site-packages\matplotlib\axes_base.py",
line 4203, in get_tightbbox
bbox = a.get_tightbbox(renderer)
File
"C:\Users\Vinod\anaconda3\lib\site-packages\matplotlib\artist.py",
line 278, in get_tightbbox
bbox = self.get_window_extent(renderer)
File
"C:\Users\Vinod\anaconda3\lib\site-packages\matplotlib\patches.py",
line 598, in get_window_extent
return self.get_path().get_extents(self.get_transform())
File
"C:\Users\Vinod\anaconda3\lib\site-packages\matplotlib\path.py", line
603, in get_extents
return Bbox([xys.min(axis=0), xys.max(axis=0)])
File
"C:\Users\Vinod\anaconda3\lib\site-packages\numpy\core_methods.py",
line 43, in _amin
return umr_minimum(a, axis, None, out, keepdims, initial, where)
ValueError: zero-size array to reduction operation minimum which has
no identity
This was a known issue and was addressed in: https://github.com/SciTools/cartopy/issues/1207. (Making sure you have the latest version of cartopy may resolve this issue).
In the meanwhile, as a workaround it was noted that you could make a call to fig.canvas.draw() before your call to plt.tight_layout().
I have a file containing data as below. you see the first column is dates. I need to plot all other columns against dates in the first column. I tried to use the code below but I receive an error message. the code an error are provided.
Data
2010-01-01,1.628,0.7063157895,0,0.9216842105
2010-01-03,1.602631579,0.6901052632,0,0.9125263158
2010-01-04,1.5818947369,0.6775789474,0,0.9043157895
2010-01-05,1.5755789473,0.6716842105,0,0.9038947368
2010-01-06,1.5605263158,0.6622105263,0,0.8983157895
2010-01-07,1.5611578948,0.6608421053,0,0.9003157895
2010-01-08,1.5598947369,0.6593684211,0,0.9005263158
2010-01-09,1.5576842105,0.6569473684,0,0.9007368421
2010-01-10,1.5462105263,0.6543157895,0,0.8918947368
2010-01-11,1.5656842105,0.6666315789,0,0.8990526316
2010-01-12,1.5517894736,0.6546315789,0,0.8971578947
2010-01-13,1.5558947368,0.6551578947,0,0.9007368421
2010-01-14,1.5638947369,0.6588421053,0,0.9050526316
2010-01-15,1.5375789474,0.6432631579,0,0.8943157895
2010-01-16,1.522631579,0.6352631579,0,0.8873684211
2010-01-17,1.5056842105,0.6254736842,0,0.8802105263
2010-01-18,1.4881052632,0.6157894737,0,0.8723157895
2010-01-19,1.4889842789,0.6251948052,0,0.8637894737
2010-01-20,1.4733383459,0.6182857143,0,0.8550526316
2010-01-21,1.4507368421,0.6009473684,0,0.8497894737
Code
import csv
import datetime as dt
import matplotlib.pyplot as plt
lis1=[]
lis2=[]
lis3=[]
lis4=[]
lis5=[]
with open('/home/omar/Desktop/finall.csv', 'rU') as f:
reader=csv.reader(f, delimiter=',')
for row in reader:
lis1.append(dt.datetime.strptime(row[0],'%Y-%m-%d'))
lis2.append(row[1])
lis3.append(row[2])
lis4.append(row[3])
lis5.append(row[4])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(lis1,lis2,lis3,lis4,lis5,'o-')
fig.autofmt_xdate()
plt.show()
Error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/spyderlib/widge/externalshell/sitecustomize.py", line 540, in runfile execfile(filename, namespace)
File "/home/omar/python/plot_txt.py", line 37, in <module>
fig.autofmt_xdate()
File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 431, in autofmt_xdate
for label in self.axes[0].get_xticklabels():
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 2614, in get_xticklabels
self.xaxis.get_ticklabels(minor=minor))
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 1161, in get_ticklabels
return self.get_majorticklabels()
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 1145, in get_majorticklabels
ticks = self.get_major_ticks()
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 1244, in get_major_ticks
numticks = len(self.get_major_locator()())
File "/usr/lib/pymodules/python2.7/matplotlib/dates.py", line 802, in __call__
self.refresh()
File "/usr/lib/pymodules/python2.7/matplotlib/dates.py", line 819, in refresh
dmin, dmax = self.viewlim_to_dt()
File "/usr/lib/pymodules/python2.7/matplotlib/dates.py", line 564, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "/usr/lib/pymodules/python2.7/matplotlib/dates.py", line 311, in num2date
return _from_ordinalf(x, tz)
File "/usr/lib/pymodules/python2.7/matplotlib/dates.py", line 214, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1
>>> Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_qt4.py", line 374, in idle_draw
self.draw()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_qt4agg.py", line 154, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 1034, in draw
func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 2086, in draw
a.draw(renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 1091, in draw ticks_to_draw = self._update_ticks(renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 945, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 889, in iter_ticks
majorLocs = self.major.locator()
File "/usr/lib/pymodules/python2.7/matplotlib/dates.py", line 802, in __call__
self.refresh()
File "/usr/lib/pymodules/python2.7/matplotlib/dates.py", line 819, in refresh
dmin, dmax = self.viewlim_to_dt()
File "/usr/lib/pymodules/python2.7/matplotlib/dates.py", line 564, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "/usr/lib/pymodules/python2.7/matplotlib/dates.py", line 311, in num2date
return _from_ordinalf(x, tz)
File "/usr/lib/pymodules/python2.7/matplotlib/dates.py", line 214, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1
The error is in your plot command.
You need to repeat what is on the x axis for each field you plot on the y axis.
So change this:
ax.plot(lis1,lis2,lis3,lis4,lis5,'o-')
to this:
ax.plot(lis1,lis2,lis1,lis3,lis1,lis4,lis1,lis5,'o-')
try:
import csv
import datetime as dt
import matplotlib.pyplot as plt
lis1=[]
lis2=[]
lis3=[]
lis4=[]
lis5=[]
with open('/home/omar/Desktop/finall.csv', 'rU') as f:
reader=csv.reader(f, delimiter=',')
for row in reader:
lis1.append(dt.datetime.strptime(row[0],'%Y-%m-%d'))
lis2.append(row[1])
lis3.append(row[2])
lis4.append(row[3])
lis5.append(row[4])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot_date(lis1,lis2,'o-',
lis1,lis3,'o-',
lis1,lis4,'o-',
lis1,lis5,'o-')
plt.show()
see documentation here: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
I'm trying to plot a data set (777 x 576) with 3D contours. This appears to be working fine until I try to place the contour under the 3d plot.
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm, pyplot
import numpy
X,Y = numpy.mgrid[:len(data), :len(data[0])]
fig = pyplot.figure('''figsize=(20, 10), dpi=800''')
ax = fig.gca(projection='3d')
ax.plot_surface(X,
Y,
data,
rstride=100,
cstride=100,
alpha=0.3,
linewidths=(.5,),
antialiased=True,
)
# cset = ax.contourf(X, Y, data, zdir='z', offset=130, cmap=cm.coolwarm)
ax.set_xlim(800, 0)
ax.set_ylim(0, 600)
ax.set_zlim(130, 170)
plt.show()
That is to say that uncommenting the ax.contourf(...) line causes the following exception:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 276, in resize
self.show()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 348, in draw
FigureCanvasAgg.draw(self)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1034, in draw
func(*args)
File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 248, in draw
for col in self.collections]
File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\art3d.py", line 456, in do_3d_projection
cedge = cedge.repeat(len(xyzlist), axis=0)
ValueError: array is too big.
In case this means anything:
len(cedge) == 35656
len(xyzlist) == 8914
35656 * 8914 = 317837584
Is there something I need to set to accommodate my data set?